Enjoy element mode of design mode (19)

Posted by youropensource on Tue, 30 Nov 2021 08:00:32 +0100

1, Introduction to Xiangyuan mode

         In the process of object-oriented programming, we sometimes face the problem of creating a large number of instances of the same or similar objects. Creating so many objects will consume a lot of system resources, which is a bottleneck to improve system performance.

        For example: black and white pieces in go and Gobang, coordinate points or colors in images, routers, switches and hubs in LAN, tables and stools in classroom, etc. These objects have many similarities. If the same parts of them can be extracted and shared, a lot of system resources can be saved. This is the background of sharing meta mode.

        1.1 definition of sharing mode

         Definition of Flyweight pattern: using sharing technology to effectively support the reuse of a large number of fine-grained objects. By sharing existing objects, it can greatly reduce the number of objects to be created and avoid the overhead of a large number of similar classes, so as to improve the utilization of system resources.

  • It is often used with the underlying development of the system to solve system performance problems. For example, the database connection pool contains created connection objects. Among these connection objects, we need to use them directly to avoid repeated creation. If we don't need them, we can create one.
  • The meta sharing mode can solve the memory waste caused by repeated objects. When a large number of similar objects in the system need a buffer pool, they can be taken from the buffer pool, which can reduce the system memory and improve efficiency.
  • The classic application scenario of meta sharing mode is pool technology. String constant pool, database connection pool and buffer pool are all applications of meta sharing mode. Meta sharing mode is an important implementation of pool technology.

        1.2 advantages and disadvantages of Yuan sharing mode

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

        Disadvantages of Xiangyuan mode:

  1. In order to share objects, some states that cannot be shared need to be externalized, which will increase the complexity of the program.
  2. Reading the external state of the shared mode will make the running time slightly longer.

      1.3 structure and principle class diagram of Xiangyuan mode

         The definition of shared meta pattern puts forward two requirements, fine granularity and shared object. Because fine granularity is required, it is inevitable that there will be a large number of objects with similar properties. At this time, we will divide the information of these objects into two parts: internal state and external state.

  • Internal state refers to the information shared by objects, which is stored in the shared element part and will not change with the change of environment.
  • External state refers to a mark that an object can rely on. It changes with the change of environment and cannot be shared.

        For example, the connection object in the connection pool, the user name, password, connection URL and other information saved in the connection object have been set when the object is created and will not change with the change of the environment. These are internal states. When each connection is to be recycled, we need to mark it as available, which are external states.

         The essence of meta sharing mode is to cache shared objects and reduce memory consumption. The schematic diagram is as follows:

          Of which:

  • UnsharedConcreteFlyweight is a non shared meta role, which contains non shared external status information info;
  • Flyweight is an abstract shared element role, which contains the shared element method operation (unshared concrete flyweight state). The external state of non shared elements is passed in the form of parameters through this method;
  • ConcreteFlyweight is a specific meta role, including the keyword key, which implements the abstract meta interface;
  • FlyweightFactory is the role of sharing element factory. It is the keyword key to manage specific sharing elements;
  • The customer role obtains the specific share through the share factory and accesses the relevant methods of the specific share.

        1.4 application of shared meta mode in JDK source code

        Integer's valueOf(), in the range of - 127 to 128, integer will fetch from the buffer pool. If not, it will create a new object and return.

          1.5 specific implementation of sharing mode

public class FlyweightPattern {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight f01 = factory.getFlyweight("a");
        Flyweight f02 = factory.getFlyweight("a");
        Flyweight f03 = factory.getFlyweight("a");
        Flyweight f11 = factory.getFlyweight("b");
        Flyweight f12 = factory.getFlyweight("b");
        f01.operation(new UnsharedConcreteFlyweight("First call a. "));
        f02.operation(new UnsharedConcreteFlyweight("Second call a. "));
        f03.operation(new UnsharedConcreteFlyweight("3rd call a. "));
        f11.operation(new UnsharedConcreteFlyweight("First call b. "));
        f12.operation(new UnsharedConcreteFlyweight("Second call b. "));
    }
}

//Non meta role
class UnsharedConcreteFlyweight {
    private String info;

    UnsharedConcreteFlyweight(String info) {
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

//Abstract meta role
interface Flyweight {
    public void operation(UnsharedConcreteFlyweight state);
}

//Specific meta role
class ConcreteFlyweight implements Flyweight {
    private String key;

    ConcreteFlyweight(String key) {
        this.key = key;
        System.out.println("Specific share yuan" + key + "Created!");
    }

    public void operation(UnsharedConcreteFlyweight outState) {
        System.out.print("Specific share yuan" + key + "Called,");
        System.out.println("Non shared meta information is:" + outState.getInfo());
    }
}

//Enjoy yuan factory role
class FlyweightFactory {
    private HashMap<String, Flyweight> flyweights = new HashMap<String, Flyweight>();

    public Flyweight getFlyweight(String key) {
        Flyweight flyweight = (Flyweight) flyweights.get(key);
        if (flyweight != null) {
            System.out.println("Specific share yuan" + key + "It already exists and was successfully obtained!");
        } else {
            flyweight = new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}

        The operation results are as follows:

Specific share yuan a Created!
Specific share yuan a It already exists and was successfully obtained!
Specific share yuan a It already exists and was successfully obtained!
Specific share yuan b Created!
Specific share yuan b It already exists and was successfully obtained!
Specific share yuan a Called, non shared meta information is:First call a. 
Specific share yuan a Called, non shared meta information is:Second call a. 
Specific share yuan a Called, non shared meta information is:3rd call a. 
Specific share yuan b Called, non shared meta information is:First call b. 
Specific share yuan b Called, non shared meta information is:Second call b

Topics: Java Design Pattern