This is the 14th day of my participation in the August More Text Challenge

Go on, go on, you can’t stop learning. Share mode is now enabled after Combo mode. Will be a review ya, will not come to see it together.

Like a sentence: “eight hours for life, eight hours for development”.

If you like it, let's stick to it!!

‘😁

An old figure

Design Mode series:

  • Java Design pattern – singleton pattern
  • Java Design Pattern – Factory Pattern (1) Simple Factory pattern
  • Java Design Pattern – Factory Pattern (2) Factory method pattern
  • Java Design Pattern – Factory Pattern (3) Abstract Factory pattern
  • Java Design pattern – Builder pattern
  • Java Design pattern – Proxy pattern
  • Java Design pattern – Adapter pattern
  • Java Design pattern – Decorator pattern
  • Java Design pattern – Bridge pattern
  • Java Design pattern – Appearance pattern
  • Java Design pattern – Composite pattern
  • Java Design pattern – Share meta pattern
  • Java Design Pattern – Template method pattern
  • Java Design pattern – Policy pattern
  • Java Design pattern – Chain of Responsibility pattern
  • Java Design Pattern – The Mediator pattern
  • Java Design Pattern – Observer Pattern (publish/subscribe pattern)
  • Continuously updated…

I. Introduction to Enjoy Yuan Model

1) Introduction:

In Java, we all know that when we create a string object, we need to look in the string constant pool. If we already have it, we don’t create it again. We just point it to that address and create it again.

Sharing is an important implementation of pooling because it would be very expensive to create a new string object every time.

2) Overview:

The Flyweight Pattern is mainly used to reduce the number of objects created to reduce memory footprint and improve performance. This type of design pattern is a structural pattern that provides a way to reduce the number of objects to improve the object structure required by the application.

The meta-share pattern attempts to reuse existing objects of the same class, and if no match is found, new objects are created.

3) Structure:

There are two states in Flyweight mode:

  1. Internal state, that is, shareable parts that do not change as the environment changes.
  2. External state refers to the part that changes with the environment and cannot be shared. The key to realize the sharing mode is to distinguish the two states in the application and externalize the external state.

The main roles of enjoy mode are as follows:

  • Abstract Flyweight: Usually an interface or abstract class that declares methods common to the concrete Flyweight metaclass. These methods can provide external data (internal state) of the Flyweight object and also set external data (external state) through these methods.
  • Concrete Flyweight role: It implements an abstract privilege metaclass called a privilege object; Storage space for internal state is provided in the concrete meta-class. Typically, we can design concrete meta-classes in conjunction with the singleton pattern, providing a unique meta-object for each concrete meta-class.
  • Unsharable Flyweight: Not all subclasses of the abstract Flyweight metaclass need to be shared. Subclasses that cannot be shared can be designed as unshared concrete flyweights. An object that does not share a concrete meta-class can be created by instantiation.
  • Flyweight Factory role: Responsible for creating and managing Flyweight roles. When a customer object requests a share object, the share factory checks whether there is a share object that meets the requirements in the system and provides it to the customer if there is one. If one does not exist, a new share object is created.

4) Usage Scenarios:

1. The system has a large number of similar objects.

2. Scenarios that require buffer pools.

If an application uses a large number of objects, and these objects cause a large storage overhead, you can consider whether to use the free element pattern.

For example, if you find that a large number of fine-grained instances of an object are generated that are essentially the same except for a few arguments, you can share a large number of single instances by moving those shared arguments out of the class and passing them in when a method is called

Ii. Case code

Case study: Tetris

The following picture is a well-known tetris in a square, if in the game Tetris, each different square is an instance object, these objects will take up a lot of memory space, the following use of share yuan mode to achieve.

Most of the numbers that we play Tetris are these square shapes, and the difference is only the color difference, so that we can extract what they have in common.

Class diagram:

There are different shapes of Tetris, and I’m only going to describe a few of them here, but the others are the same and I won’t write them out.

“I”, “J”, “L” take these three characters to represent the Tetris ha 😁😁, more detailed in the code contains explanation.

In AbstractBox we define public Abstract String getShape(); This is abstracting the shape up one more layer.

The IBox, LBox, and OBox inheritance implement getShape() methods to represent different shapes, respectively. This is an internal state in the share mode state.

The external state is the color of the various shapes.

Code:

Take a look at the following code in detail:

Tetris has different shapes, and abstractBoxes can be drawn up from these shapes to define common properties and behaviors.

public abstract class AbstractBox {
    public abstract String getShape(a);

    public void display(String color) {
        System.out.println("Square shape:" + this.getShape() + "Color:"+ color); }}Copy the code

Different shapes, IBox class, LBox class, OBox class

public class IBox extends AbstractBox {

    @Override
    public String getShape(a) {
        return "I"; }}public class LBox extends AbstractBox {

    @Override
    public String getShape(a) {
        return "L"; }}public class OBox extends AbstractBox {

    @Override
    public String getShape(a) {
        return "O"; }}Copy the code

A factory class (BoxFactory) is provided to manage the meta-objects (aka AbstractBox subclass objects). Only one factory class object is required, so you can use the singleton pattern. And give the factory class a method to get the shape.

public class BoxFactory {

    private static HashMap<String, AbstractBox> map;
	
    // Initialize in the constructor
    private BoxFactory(a) {
        map = new HashMap<String, AbstractBox>();
        map.put("I".new IBox());
        map.put("L".new LBox());
        map.put("O".new OBox());
    }

    // Provide a method to get the factory class object
    public static final BoxFactory getInstance(a) {
        return SingletonHolder.INSTANCE;
    }

    Static inner class to implement the singleton pattern
    private static class SingletonHolder {
        private static final BoxFactory INSTANCE = new BoxFactory();
    }

    // Get the graph object by name
    public AbstractBox getBox(String key) {
        returnmap.get(key); }}Copy the code

Client:

public class Client {

    public static void main(String[] args) {
        BoxFactory boxFactory = BoxFactory.getInstance();
        AbstractBox box = boxFactory.getBox("I");
        box.display("Yellow");

        AbstractBox box2 = boxFactory.getBox("I");
        box2.display("Green");
        
        System.out.println(box==box2);
        System.out.println(box.equals(box2));
   	    /** * square shape: I Color: yellow * square shape: I color: green * true * true */}}Copy the code

We can see that the two objects are the same even though their colors are different. Public is implemented.

Third, summary

1, the advantages of

  • Greatly reduces the number of similar or identical objects in the memory, saving system resources and improving system performance
  • The external state in the share mode is relatively independent and does not affect the internal state

2. Disadvantages:

In order to make the object can be shared, it is necessary to externalize part of the state of the shared object, separate the internal state from the external state, and make the program logic complicated

The complexity of the system is increased, and the external state needs to be separated from the internal state, and the external state has the nature of inherent, should not change with the change of the internal state, otherwise it will cause the chaos of the system.

3. Usage Scenarios:

  • A system has a large number of identical or similar objects, resulting in a large memory consumption.
  • Most of the state of an object can be externalized, and these external states can be passed into the object.
  • The use of the share pattern requires maintaining a pool of share objects, which requires a certain amount of system resources, so it should be worthwhile to use the share pattern only when the share objects need to be reused multiple times.

4. Application Examples:

The String constant pool

Database connection pool

4. Talk to yourself

Hi, if you happen to read this article and think it’s good for you, give it a thumbs up and let me feel the joy of sharing, Crab. 🤗

If there is something wrong, please don’t add to it!!

Similarly, if there is any doubt, please leave a message or private message, we will reply to you in the first time.

Ongoing update