[Structural] Flyweight mode (Flyweight)

Flyweight mode (Flyweight)

Use sharing technology to efficiently support large numbers of fine-grained objects. (The objects of the business model are subdivided to obtain more scientific and reasonable objects)

Applicable scene

  • An application uses a large number of objects.
  • This is entirely due to the use of a large number of objects, resulting in a large storage overhead.
  • Most of an object's state can be made external.
  • If you remove the external state of objects, you can replace many groups of objects with relatively few shared objects.
  • The application does not rely on object identification. Because Flyweight objects can be shared, identity tests will return true for conceptually distinct objects.
    Insert image description here

✦ Flyweight describes an interface through which Flyweight can accept and act on external states.
✦ ConcreteFlyweight implements the Flyweight interface and adds storage space for internal state (if any). ConcreteFlyweight objects must be shareable . The state it stores must be internal, that is, it must be independent of the ConcreteFlyweight object's scene.
✦ Not all Flyweight subclasses need to be shared. The Flyweight interface makes sharing possible, but it does not force sharing. At some level in the Flyweight object structure, UnsharedConcreteFlyweight objects usually have ConcreteFlyweight objects as child nodes.
✦ FlyweightFactory creates and manages Flyweight objects; ensures reasonable sharing of Flyweights. When the user requests a Flyweight, the FlyweightFactory object provides a created instance or creates an instance if it does not exist.
✦ Client maintains a reference to Flyweight; calculates or stores the external state of one or more Flyweights.

Flyweight mode example code (Java)

import java.util.*;

// Flyweight
abstract class Shape {
    
    
    protected String color;
    public abstract void draw(int x, int y);
}

// ConcreteFlyweight
class Circle extends Shape {
    
    
    public Circle(String color) {
    
    
        this.color = color;
    }
    @Override
    public void draw(int x, int y) {
    
    
        System.out.println("draw a color:" + color + " circle x:" + x + " y:" + y);
    }
}

// FlyweightFactory
class ShapeFactory {
    
    
	// FlyweightFactory创建并管理Flyweight对象;
	// 确保合理地共享 Flyweight ,当用户请求一个 Flyweight 时,FlyweightFactory 对象提供一个己创建的实例或者在不存在时创建一个实例。
    private Map<String, Shape> map = new HashMap<String, Shape>();

    public Shape getShape(String key) {
    
    
        if (!map.containsKey(key)) {
    
    
            map.put(key, new Circle(key));
            System.out.println("create color:" + key + " circle");
        }
        return map.get(key);
    }
}

public class FlyWeightMain {
    
    
    public static void main(String[] args) {
    
    
        ShapeFactory factory = new ShapeFactory();

        Random random = new Random();
        String[] colors = {
    
    "red", "blue", "green", "white", "black"};

        for (int i = 1; i <= 100; i++) {
    
    
            int x = random.nextInt(colors.length); // [0 ~ 4]
            Shape shape = factory.getShape(colors[x]);

            System.out.print("第" + i + "个圆:");
            shape.draw(random.nextInt(2022), random.nextInt(528));
        }
    }
}

For details on other design patterns, please refer to other blog posts in this column.
Special thanks to zst_2001 for his help during the preparation for the soft exam. Posted in the personal space of blogger B station
zst_2001

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/128486991