Design Pattern---FlyWeight Pattern

1 Introduction

In programming, we sometimes face the scenario of creating a large number of instances of the same or similar objects, such as the black and white pieces of the Go game, and the desks and chairs in the classroom. If similar places are abstracted and shared, it can save a lot of system resources and improve system performance, which corresponds to the Flyweight mode.

2 Definitions

Flyweight Pattern: Use sharing techniques to efficiently support the reuse of a large number of fine-grained objects. It greatly reduces the number of objects that need to be created by sharing existing objects and avoids the overhead of a large number of similar classes, thereby improving the utilization of system resources.

3 Internal state and external state

Internal state refers to the information shared within Flyweight, such as classroom chairs, whose material, shape, specification and structure are all the same, and can be completely shared.

External state refers to information that Flyweight cannot share, and this information will change as the environment changes, such as the current user of classroom desks and chairs.

4 Structure and Implementation

Flyweight mode contains 4 important roles, namely:

1. The abstract FlyWeight role is the base class of all specific Flyweight classes, and is the public interface that specific Flyweight specifications need to implement. Non-Flyweight external states are passed in through methods in the form of parameters.

2. Concrete Flyweight role: Implement the interface specified in the abstract Flyweight role.

3. Unsharable Flyweight role: It is an external state that cannot be shared. It is injected into the relevant methods of specific Flyweight in the form of parameters.

4. Flyweight Factory role: responsible for creating and managing Flyweight roles. When a client object requests a flyweight object, the flyweight factory checks whether there is a flyweight object that meets the requirements in the system, and if it exists, it is provided to the client; if it does not exist, a new flyweight object is created.

The structure is shown in the following figure (the figure is from reference 2):

5 Advantages and disadvantages

The main advantage of the Flyweight pattern is that only one copy of the same object is saved, which reduces the number of objects in the system, thereby reducing the pressure on memory caused by fine-grained objects in the system.

Its main disadvantages are:

1. In order to make objects sharable, some states that cannot be shared need to be externalized, which will increase the complexity of the program.

2. Reading the external state of Flyweight will make the runtime slightly longer.

6 Code Examples

For the same website, we do not need to create different instance objects, just use different users, and different users for the same instance.

6.1 Define User User

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-22 15:23
 **/
@Data
@AllArgsConstructor
public class User {
    /**
     * 用户名
     */
    private String name;

    /**
     * 简介
     */
    private String desc;

}

6.2 Abstract Flyweight Website

**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-22 11:28
 * @desc: 抽象享元接口
 **/
public interface Website {

    /**
     * 发布博客
     * @param user 用户
     */
    void postBlog(User user);


    /**
     * 上传图片
     * @param user 用户
     */
    void uploadPicture(User user);
}

6.3 Concrete Flyweight ConcreteWebsite

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-22 15:22
 **/
public class ConcreteWebsite implements Website{

    @Override
    public void postBlog(User user) {
        System.out.println(MessageFormat.format("{0}用户,简介是{1},上传博客", user.getName(), user.getDesc()));
    }

    @Override
    public void uploadPicture(User user) {
        System.out.println(MessageFormat.format("{0}用户,简介是{1},上传图片", user.getName(), user.getDesc()));
    }
}

6.4 Factory

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-22 15:28
 **/
public class Factory {
    private Map<String, Website> websites = new HashMap<>();


    public  Website getWebsite(String key){
        if (websites.containsKey(key)){
            return websites.get(key);
        }
        Website website = new ConcreteWebsite();
        websites.put(key, website);
        return website;
    }
}

6.5 Main program

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-22 11:27
 **/
public class MainClass {
    public static void main(String[] args) {
        Factory factory = new Factory();
        Website website11 = factory.getWebsite("csdn");
        Website website12 = factory.getWebsite("csdn");
        Website website21 = factory.getWebsite("zhihu");
        Website website22 = factory.getWebsite("zhihu");

        website11.postBlog(new User("张三", "助理工程师"));
        website11.uploadPicture(new User("张三", "助理工程师"));
        website12.postBlog(new User("李四", "中级工程师"));
        website12.uploadPicture(new User("李四", "中级工程师"));

        website21.postBlog(new User("王五", "副高级工程师"));
        website21.uploadPicture(new User("王五", "副高级工程师"));
        website22.postBlog(new User("赵六", "高级工程师"));
        website22.uploadPicture(new User("赵六", "高级工程师"));
    }
}

6.6 Running Results

7 Quotes 

1 "Dahua Design Patterns"

Flyweight mode (detailed version)

8 Source code

https://github.com/airhonor/design-pattern-learning/tree/main/src/com/hz/design/pattern/flyweight

 

Guess you like

Origin blog.csdn.net/honor_zhang/article/details/120901850