Design patterns

The flyweight pattern

The enjoy element pattern, also known as the lightweight pattern, is an object structure pattern because the enjoy element pattern requires that the objects that can be shared be fine-grained objects. The share element pattern is an implementation of object pooling, essentially caching shared objects to reduce memory consumption.

The most common example is gobang, in which the pieces are divided into black and white, which is the internal state, which cannot be changed. The positions of the two sides are dynamic, so the coordinates of the chess pieces are the external state. Using the enjoy element mode, only two objects need black and white, greatly reducing memory consumption.

Abstract Enjoy yuan role Gobang

package com.wangscaler.flyweight;

/ * * *@author wangscaler
 * @dateThou 2021.06.29 * /
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(a) {
        System.out.println(this.chess + "(" + this.x + "," + this.y + ")"); }}Copy the code

Specific enjoy yuan role Black, the realization of the point method

package com.wangscaler.flyweight;

/ * * *@author wangscaler
 * @dateThou 2021.06.29 * /
public class Black extends Gobang {

    public Black(a) {
        super("Spot");
    }

    @Override
    public void point(int x, int y) {
        this.x = x;
        this.y = y; printPoint(); }}Copy the code

Specific enjoy yuan role White

package com.wangscaler.flyweight;

/ * * *@author wangscaler
 * @dateThou 2021.06.29 * /
public class White extends Gobang {
    public White(a) {
        super("白子");
    }

    @Override
    public void point(int x, int y) {
        this.x = x;
        this.y = y; printPoint(); }}Copy the code

GobangFactory, get black and white, if not initialized, if directly provided

package com.wangscaler.flyweight;

import java.util.HashMap;

/ * * *@author wangscaler
 * @dateThou 2021.06.29 * /
public class GobangFactory {
    private static GobangFactory gobangFactory = new GobangFactory();

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

    private GobangFactory(a) {}public static GobangFactory getInstance(a) {
        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("Chess pieces are not of the correct type."); }}return cache.get(type);
    }

    public void getCount(a) {
        System.out.println("Current number of HashMaps"+ cache.size()); }}Copy the code

main

package com.wangscaler.flyweight;

import java.util.Random;

/ * * *@author wangscaler
 * @dateThou 2021.06.29 * /
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(); }}}}Copy the code

Enjoy meta schema in source code

Integer in JAVA, which was written about earlier in this article at JAVA Error Prone point 2, will not be covered here.

conclusion

Enjoy meta-pattern, as the name implies, enjoy is sharing, and meta-pattern is object, which is the pattern of sharing objects.

Enjoy the role of the meta-mode:

  1. Abstract Enjoyment meta role: the base class of all concrete enjoyment metaclasses, the abstract class of the product, defines the object’s external state (non-shareable state, which can change) and internal state (which does not change as the environment changes). The non-enjoyment meta’s external state is passed in as a parameter through methods.
  2. Specific enjoyment role: a concrete product object that implements the interface specified in the abstract enjoyment role.
  3. Non-enjoyed role: An external state that cannot be shared. Generally does not appear in xiangyuan factory.
  4. Xiang Yuan factory role: Responsible for creating and managing the Xiang Yuan role. When a customer requests a share object, the share factory checks whether the required share object exists in the system. If no, it creates one. If it exists, it is provided directly.

Usage scenario:

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

2, identifies an object with an identifier (such as W and B in Gobang, -127 to 128 in Integer). If there is one in memory, it is fetched directly, and if there is not, it is initialized.

3. The essence of the share element mode is separation and sharing: separation of change and invariance, and sharing invariance. Realize the reuse of objects

The resources

  • JAVA Design Patterns