Design Pattern Fifteen--Flyweight Pattern

Design Patterns

flyweight pattern

Flyweight pattern, also known as lightweight pattern, is an object structure pattern, because Flyweight pattern requires that objects that can be shared must be fine-grained objects. Flyweight mode is an implementation of object pooling, the essence is to cache shared objects and reduce memory consumption.

The most common example is Gobang. In Gobang, the pieces are divided into two colors: black and white. This is the internal state and cannot be changed. The positions of the two players move dynamically, so the coordinates of the pawns are the external states. Using Flyweight mode, only two objects, black and white, are needed, which greatly reduces memory consumption.

Abstract flyweight character Gobang

package com.wangscaler.flyweight;

/**
 * @author wangscaler
 * @date 2021.06.29 18:12
 */
public abstract class Gobang {
    protected int x;
    protected int y;
    protected String chess;

    public Gobang(String chess) {
        this.chess = chess;
    }

    public abstract void point(int x, int y);

    public void printPoint() {
        System.out.println(this.chess + "(" + this.x + "," + this.y + ")");
    }

}
复制代码

The specific flyweight role Black implements the point method

package com.wangscaler.flyweight;

/**
 * @author wangscaler
 * @date 2021.06.29 18:12
 */
public class Black extends Gobang {

    public Black() {
        super("黑子");
    }

    @Override
    public void point(int x, int y) {
        this.x = x;
        this.y = y;
        printPoint();
    }
}
复制代码

Specific flyweight role White

package com.wangscaler.flyweight;

/**
 * @author wangscaler
 * @date 2021.06.29 18:12
 */
public class White extends Gobang {
    public White() {
        super("白子");
    }

    @Override
    public void point(int x, int y) {
        this.x = x;
        this.y = y;
        printPoint();
    }
}
复制代码

Flyweight factory role GobangFactory, get black and white, initialize if not, provide directly

package com.wangscaler.flyweight;

import java.util.HashMap;

/**
 * @author wangscaler
 * @date 2021.06.29 18:12
 */
public class GobangFactory {
    private static GobangFactory gobangFactory = new GobangFactory();

    private final HashMap<String, Gobang> cache = new HashMap<String, Gobang>();

    private GobangFactory() {
    }

    public static GobangFactory getInstance() {
        return gobangFactory;
    }

    public Gobang getChessmanObject(String type) {
        if (!cache.containsKey(type)) {
            if (type.equals("B")) {
                cache.put(type, new Black());
            } else if (type.equals("W")) {
                cache.put(type, new White());
            } else {
                System.out.println("棋子类型不正确");
            }
        }
        return cache.get(type);
    }

    public void getCount() {
        System.out.println("当前hashmap的个数" + cache.size());
    }

}
复制代码

main

package com.wangscaler.flyweight;

import java.util.Random;

/**
 * @author wangscaler
 * @date 2021.06.29 18:12
 */
public class Flyweight {
    public static void main(String[] args) {
        GobangFactory gobangFactory = GobangFactory.getInstance();
        Random random = new Random();
        Gobang gobang = null;
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                gobang = gobangFactory.getChessmanObject("B");
            } else {
                gobang = gobangFactory.getChessmanObject("W");
            }
            if (gobang != null) {
                gobang.point(i, random.nextInt(15));
                gobangFactory.getCount();
            }
        }
    }
}
复制代码

Flyweight pattern in source code

Integer in JAVA, this previous article Java error-prone point 2 has been written, so I won't repeat it.

Summarize

Flyweight mode, as the name implies, is to share, and yuan is the object, that is, the mode of sharing objects.

The role of the flyweight pattern:

  1. Abstract flyweight role: It is the base class of all concrete flyweight classes, that is, the abstract class of the product, which defines the external state of the object (unshared state, can be changed) and internal state (will not change with the environment) , the non-Flyweight external state is passed in through the method in the form of parameters.
  2. Concrete flyweight role: a concrete product object that implements the interface specified in the abstract flyweight role.
  3. Non-Flyweight roles: are external states that cannot be shared. Generally not in Flyweight Factory.
  4. Flyweight Factory Role: Responsible for creating and managing Flyweight roles. When a client requests a flyweight object, the flyweight factory checks whether a flyweight object that meets the requirements already exists in the system, and if it does not exist, it will create one; if it exists, it will be provided directly.

scenes to be used:

1. There are many objects, and the state of the objects can be externalized.

2. Use the identification code to identify the object (like W and B in Gobang, -127 to 128 in Integer), if there is one in the memory, take it out directly, if not, initialize it.

3. The essence of Flyweight mode is separation and sharing: separation of change and invariance, and sharing of invariance. Reuse of objects

References

Guess you like

Origin juejin.im/post/6979406730207690765