Flyweight model of java design pattern (11)

Life requires struggle. Only if you struggle, you will have a clear conscience after failure; life is a one-way road, and only when you struggle can you have a bright future; there are many competitors in life, because there are so many competitors , So we have to fight more!

Design pattern learning, I will blog about 23 design patterns in the near future , so stay tuned~
—2021/1/12

definition

It is also called the flyweight model ; it uses sharing technology to effectively support a large number of fine-grained objects.

Baidu Encyclopedia

scenes to be used

If an application uses a large number of objects, and these objects cause a lot of storage overhead, you can consider whether you can use the flyweight model.

For example, if you find that a large number of fine-grained instances of an object are generated, and these instances are basically the same except for a few parameters, if you move those shared parameters outside of the class and pass them in when the method is called, you can By sharing a large number of single instances.

problem analysis

Suppose I want to create a square, a rectangle, a circle, a triangle,

The usual thinking should be: use the factory model, because they are very similar, and they belong to a series of'products', but they will create multiple instances, causing memory waste

Solution:
Integrate them together and share related code and data, which is somewhat similar to the singleton model. Here, the column Flyweight model is used.

The difference between Flyweight mode and singleton mode

  • Singleton mode is the whole system shares one instance
  • Flyweight mode is that the entire system shares several objects of the same type, and the shared objects of the flyweight mode are allocated as needed, and will be created automatically if they do not exist.
  • Singleton mode will not create a second instance
  • The shared object in the Flyweight model must be private to the thread. For example, shared bicycles. Although they are shared, they are yours, but they are borrowed and repaid, and shared to some extent.

External state and internal state

  • The internal state can be shared , stored in the Flyweight, and will not vary with changes in the environment.
  • The external state cannot be shared , it changes with the change of the environment, so the external state is maintained by the client (because the change of the environment is caused by the client).

It doesn't matter if you don't understand here, you will understand after reading the code!

UML类图(2.1):
Insert picture description here

Role analysis

  • Abstract Flyweight : specifies the methods that must be implemented for the specific Flyweight , and the external state is passed in through this method in the form of parameters. In Java, abstract classes and interfaces can be used.

  • ConcreteFlyweight : A method for implementing abstract roles. If there is an internal state, it is responsible for providing storage space for the internal state.

  • FlyweightFactory role (FlyweightFactory) : responsible for creating and managing FlyweightFactory roles. To achieve the purpose of sharing, the realization of this role is the key!

  • Client role (Client) : maintains references to all flyweight objects, and also needs to store the corresponding extrinsic state

It doesn't matter if you don't understand here, you will understand after reading the code!

Internal status code implementation

IShape (Abstract Flyweight Role):

public interface IShape {
    
    
    public void showShape();
}

ShapeImpl (specific Flyweight role):

public class ShapeImpl  implements IShape{
    
    

    //内部享元部分 (形状)
    private String type = "";

    public ShapeImpl(String type) {
    
    
        this.type = type;
    }

    @Override//外部享元角色
    public void showShape() {
    
    
        Log.i("享元模式","绘制 "+type+" 成功 ");
    }
}

The type here is the internal state, which can be shared. It will not change with the change of the environment.

ShapeFactory (Flyweight Factory Role)

public class ShapeFactory {
    
    

    HashMap<String,ShapeImpl> hashMap = new HashMap<>();
	//设置type
    public IShape getShape(String type){
    
    
        if (!hashMap.containsKey(type)) {
    
    
                hashMap.put(type,new ShapeImpl(type));
       }
        return hashMap.get(type);
    }

	//获取hashMap数量
    public int getShapeSize(){
    
    
        return hashMap.size();
    }
}

Why use HashMap here?

HashMap features:

  • The bottom layer of HashMap is mainly based on arrays and linked lists.
  • The reason for the relatively fast query speed is mainly because it determines the storage location by calculating the hash code.
  • HashMap can be serialized. It is not thread safe.
  • HashMap can ensure that the key is unique

Because HashMap can ensure that the key is unique, if a key is passed in, the corresponding object is returned if it exists. If the object is not created, the effect of'singleton' is achieved.

Because the HashMap thread is not safe, the flyweight mode is not recommended to be used in multi-threaded situations.

testing method:

ShapeFactory shapeFactory = new ShapeFactory();
IShape shape1 = shapeFactory.getShape("正方形");
IShape shape2 = shapeFactory.getShape("正方形");
IShape shape3 = shapeFactory.getShape("三角形");
IShape shape4 = shapeFactory.getShape("正方形");
shape1.showShape();
shape2.showShape();
shape3.showShape();
shape4.showShape();

Log.i("享元模式","总个数为: "+shapeFactory.getShapeSize()+"");

Log图(1.1): It
Insert picture description here
can be seen that although 3 squares are stored, the total number of printed ones is still 2, because there are only 2 types (square and triangle) inside

But it can be seen that the code is only used for the internal state, there is no external state, and then add the external state

External status code implementation

IShape (Abstract Flyweight Role):

public interface IShape {
    
    
    //由客户端输入外部状态 
    public void showShape(Color color);
}

The color color here is the external state, the external state cannot be shared , the external state is input by the customer, and it changes with the change of the environment.

Color (external state):

public class Color {
    
    
    private String color = "";
    public Color(String color) {
    
    
        this.color = color;
    }
    public String getColor() {
    
    
        return color;
    }
}

ShapeImpl (specific Flyweight role):

public class ShapeImpl  implements IShape{
    
    

    //共享部分 (形状)
    private String type = "";

    public ShapeImpl(String type) {
    
    
        this.type = type;
    }

    @Override//外部享元角色
    public void showShape(Color color) {
    
    
        Log.i("享元模式","绘制 "+type+" 成功 颜色为:"+color.getColor());
    }
}

The type here is the internal state, which can be shared. It will not change with the change of the environment.

ShapeFactory (Flyweight Factory Role)

public class ShapeFactory {
    
    

    HashMap<String,ShapeImpl> hashMap = new HashMap<>();

    public IShape getShape(String type){
    
    
        if (!hashMap.containsKey(type)) {
    
    
                hashMap.put(type,new ShapeImpl(type));
       }
        return hashMap.get(type);
    }
    public int getShapeSize(){
    
    
        return hashMap.size();
    }
}

testing method:

ShapeFactory shapeFactory = new ShapeFactory();

IShape shape1 = shapeFactory.getShape("正方形");
IShape shape2 = shapeFactory.getShape("正方形");
IShape shape3 = shapeFactory.getShape("三角形");
IShape shape4 = shapeFactory.getShape("正方形");

shape1.showShape(new Color("红色"));
shape2.showShape(new Color("红色"));
shape3.showShape(new Color("黄色"));
shape4.showShape(new Color("黑色"));

Log.i("享元模式","总个数为: "+shapeFactory.getShapeSize()+"");

Log图(1.2): The
Insert picture description here
external state is open to the outside world, defined by the user, and cannot be shared.The
internal state is shared. If it has the same value, it is not recreated, and the shared one is used.

Complete code

Go to the Design Patterns/Design Principles homepage

Originality is not easy, your likes are your greatest support for me, leave your likes~

Guess you like

Origin blog.csdn.net/weixin_44819566/article/details/112523407