preface

The xiangyuan pattern is also a structural pattern.

The principle and implementation of the enjoy element pattern are simple, but the application scenarios are relatively narrow. It is related to, but different from, the caching and pooling patterns we are familiar with now.

The share element pattern emphasizes spatial efficiency, for example, how a large data model object can use as little memory as possible and provide reusable capabilities; The caching mode emphasizes time efficiency, for example, caching activity data and inventory data, which may take up a lot of memory and disk space, but must be responsive to the user’s purchase request at the start of the campaign. In other words, they essentially solve different types of problems.

directory

A, definitions,

Using shared objects effectively supports a large number of fine-grained objects.

Instead of holding all of our data in each object, we can load more objects into our limited memory capacity by sharing the same state shared by multiple objects.

As you can see from this definition, the core problem that the enjoy element pattern solves is to save memory space by finding common features between similar objects and then reusing those features.

Two, mode principle analysis

Let’s start with the concept of internal and external states

  • Internal state: state that does not change with the environment, commonly known as immutable object. For example, Integer object initialization in Java is a cache of -127 to 128 values, which remain unchanged no matter how Integer is used.

  • External state: a state that changes as the environment changes. It is usually unique to an object and cannot be shared. Therefore, it can only be saved by the client. The external state is needed because the client needs different customizations.

    Public interface Flyweight {void operation(int state); }

    Public class FlyweighFactory {// Define a pool container public Map<String,Flyweight> pool = new HashMap<>();

    public FlyweighFactory() { pool.put("A", new ConcreteFlyweight("A")); // Add the corresponding internal state to pool.put("B", new ConcreteFlyweight("B")); pool.put("C", new ConcreteFlyweight("C")); } public Flyweight getFlyweight(String key) {if (pool.containsKey(key)) {system.out.println ("=== = Key: "+key); return pool.get(key); } else {system.out.println ("=== ", key: "+key); Flyweight flyweightNew = new ConcreteFlyweight(key); pool.put(key,flyweightNew); return flyweightNew; }}Copy the code

    }

    Public class ConcreteFlyweight implements Flyweight {private String Implements Flyweight; private String implements Flyweight; private String implements Flyweight; public ConcreteFlyweight(String key) { this.uniqueKey = key; }

    @override public void operation(int state) {system.out.printf ("=== %s%n",uniqueKey,state); }Copy the code

    } / / unshared specific Flyweight public class UnsharedConcreteFlyweight implements the Flyweight {

    private String uniqueKey; public UnsharedConcreteFlyweight(String key) { this.uniqueKey = key; } @override public void operation(int state) {system.out.println ("=== ");} @override public void operation(int state) {system.out.println ("=== "); }Copy the code

    }

If the key is the same, then reuse the object.

There are similar operations in Java. For example, in Java Integer object initialization caches -127 through 128 values, which remain unchanged no matter how Integer is used.

public static Integer valueOf(int i) {
	if (i >= IntegerCache.low && i <= IntegerCache.high)
		return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
Copy the code

Iii. Usage Scenarios

  • A large number of objects are repeatedly created in the system. For example, the same product display pictures, details, text introduction, etc

  • Objects that are highly relevant and reusable. For example, the company’s organizational structure, personnel basic information, website classification information

  • Scenarios that require buffer pools

Four advantages,

  • Reduce memory consumption and server cost

  • Aggregate immutable objects of the same class to improve the reusability of objects

Five, the disadvantages

  • The exchange of time for space indirectly increases the implementation complexity of the system and improves the complexity of the system. It is necessary to separate the external state and internal state. When using the class written by oneself as the external state, it must be rewrittenequalsandhashCodeMethod, so the external state is bestJavaBasic types are flags