This paper mainly introduces the concept and usage of share mode, stateful share mode and compound share mode.
Model background
The share mode is a more complex one. In some systems, a large number of objects may be required. For example, pawn in the game, black and white in the Go system, if we need a new object every time, then the system will create a large number of objects. This can put a lot of strain on the system and, in the case of Java, trigger a lot of GC. So how to optimize the design, avoid the system to create a large number of the same or similar objects is the goal of the meta-mode.
A prime example: in a crowded city, everyone needs to learn to ride a bike. If everyone has a bicycle, how much will it cost? But with shared bikes, things are different. We only need a few shared bikes to make bikes available to everyone. This shared bike is the idea of the yuan model.
Definitions & Concepts
The reuse of a large number of fine – grained objects is effectively supported by sharing technology. The system only uses a small number of objects, and these objects are very similar, the state change is very small, can realize the object multiple reuse. Because the share mode requires that the objects that can be shared must be fine grained objects, it is also called lightweight mode, which is an object structure mode.
The principle of
I understand the metadata sharing mode as the metadata sharing mode. What is metadata? Metadata The data that describes data attribute information is called metadata, and that metadata is the attribute of data. That is, the element is the same for all data (e.g. files have attributes such as size, type, and filename).
Sharing mode is also to extract the part of the invariable state in a large number of similar or identical objects in the system, so that the part of the state change share this part. Therefore, the key of sharing mode is to distinguish the internal and external state of the object.
Internal states (constant) : Those that do not change due to changing circumstances. For example, to describe a paragraph of text, ABC is ABC.
External states (changes) : Unshareable states that change as the environment changes. For example, ABC text is song style, boldface and so on.
** We use the share mode to create singletons or small amounts of invariant internal state. Let the changing, unshareable external state be passed to the shared object in the form of arguments. ** This is also why objects that can be shared must be fine-grained. Generally, in a heap of objects, the same parts are relatively small, and these parts can be removed as shared objects.
Sharing mode structure is more complex, generally also need to combine with factory, singleton mode.
elements
-
Abstract share metaclass (Flyweight)
- An interface or abstract class that declares public methods and provides methods with unchanging internal state and set external state.
-
ConcreteFlyweight
- Objects that need to be built with shared, state-invariant properties and methods. The singleton pattern is typically used to design concrete meta-classes.
-
Enjoy sharing specific metaclass (UnsharedConcreteFlyweight)
- There are subclasses of meta-abstract classes that we don’t need to share, and those classes just go new.
-
FlyweightFactory
- A factory that creates all of the share objects, with a cache pool inside that caches shared share objects. When objects are needed, they are fetched from the pool and then created. Its main role is to create pools that act as pools.
- It has two functions: creating pool objects and caching pool objects.
-
External state classes (not required, only required if the share object has external state, not required if it is only shared)
- States that cannot be shared. These objects represent the changing state of the share object and need to be passed to the share object.
According to the customization requirements of the share object, there are two share modes:
-
Pure meta-sharing mode: All concrete meta-classes can be shared. There are no non-shared concrete meta-classes.
-
Composite share mode: Sometimes you want to combine multiple share objects in a pool with their external state set at the same time. This allows the share objects to have the same external state at the same time.
UML
Here is a stateless share mode:
implementation
Abstract enjoy metaclass
public interface Flyweight {
/** Internal changes */
void printIntrinsicState(a);
/ * *@paramExtrinsicState External changes allow external control */
void op(String extrinsicState);
}
Copy the code
Concrete enjoy metaclass
public class ConcreteFlyweight1 implements Flyweight {
/** This internal state is the smallest granularity that the object can be partitioned into. In this state, the system creates as many of these meta-classes as it needs. * /
@Override
public void printIntrinsicState(a) {
System.out.println("intrinsicState1");
}
/** Displays external changes */
@Override
public void op(String extrinsicState) { printIntrinsicState(); System.out.println(extrinsicState); }}Copy the code
Non-shared concrete share metaclass
public class UnsharedConcreteFlyweight implements Flyweight {
/** Not those states inside the meta. * /
private String otherStates;
@Override
public void printIntrinsicState(a) {
System.out.println("intrinsicState");
}
@Override
public void op(String extrinsicState) {
// Output internal state
printIntrinsicState();
// Output other states
System.out.println(otherStates);
// Outputs the state of the external controlSystem.out.println(extrinsicState); }}Copy the code
Enjoy yuan factory class
public class FlyweightFactory {
/ / the singleton
private static FlyweightFactory instance = new FlyweightFactory();
/ / the buffer pool
private HashMap<String, Flyweight> flyweights = new HashMap<>();
// Store the shared metadata object
public FlyweightFactory(a) {
Flyweight fw1 = new ConcreteFlyweight1();
Flyweight fw2 = new ConcreteFlyweight2();
flyweights.put("1", fw1);
flyweights.put("2", fw2);
}
/ / to get
public Flyweight getFlyweight(String key) {
if (flyweights.containsKey(key)) {
// If the cache exists, return it directly
return flyweights.get(key);
} else {
// Create a cache and return if it does not exist
Flyweight fw = new ConcreteFlyweight1();
flyweights.put(key, fw);
returnfw; }}public static FlyweightFactory getInstance(a) {
returninstance; }}Copy the code
Add external changes: External changes can be objects of concrete classes, but for simplicity, they are just passed in as strings.
Flyweight f1 = FlyweightFactory.getInstance().getFlyweight("1");
f1.op("you are one");
// The op behavior of F1 is changed, but F1 is still the same
f1.op("you are not one");
Copy the code
The advantages and disadvantages
advantages
- Reduce the number of objects in memory so that only one of the same and similar objects remains.
disadvantages
- It increases the complexity of the system and requires the separation of internal and external states, which makes it impossible for people to look at it as a whole. It complicates the logic of the program and makes it harder to understand.
- The disadvantage is mainly in the relationship between internal state and external state.
Usage scenarios
- When a large number of identical or duplicate objects exist in the system, you can try to use the share mode. The main starting point is to save memory and reduce the memory overhead of objects.
- Scenarios where buffer pools are required
The String class in the JDK uses the meta schema. String, two identical strings are actually the same object, both have the same address. Related pool technology and enjoy yuan actually have this similar idea.
conclusion
** When there are a large number of identical and similar objects in the system, try to use the share mode. The first thing to do is to separate the internal and external states of these objects. The internal state is the metadata object, created using an abstract factory. The external state is passed to the share object to give the share object a different state (it is possible that this external state does not need to be passed to the share object). ** Note that you need a singleton factory to create the share object.
The attached
Related code: github.com/zhaohaoren/…
If there are code and article problems, also please correct! Thank you!