In this article we introduce the Flyweight pattern, Flyweight represents the lightweight meaning that the sharing meta-mode is an implementation of the object pool. The enjoy meta-mode is used to minimize memory usage, it is suitable for scenarios where there are a large number of duplicate objects, caches shareable objects to achieve object sharing and avoids the effects of creating too many objects, which can improve performance, avoid memory removal and frequent GC, etc.
A classic use case of the binary mode is the data structure used in the graphical display of the text system, and the type of characters that a text system can display is dozens of hundred, so define all the underlying character objects, store the display shape of each character and other formatted data, etc. without having to create a new object every time. This avoids creating thousands of duplicate objects and greatly increases the reuse rate of objects.
Reprint Please specify source: http://blog.csdn.net/self_study/article/details/51870660.
PS: The technology is interested in the same shoe plus group 5,446,459,721 Exchange.
Total catalog of design patterns
Java/android design mode Learning Notes directory
features
use shared objects to effectively support a large number of fine-grained objects.
Shared mode supports the reuse of a large number of fine-grained objects, so the enjoy meta-pattern requires that objects that can be shared must be fine-grained objects . Before we understand the meta-mode, we need to understand two concepts: internal state, external state:
- Internal state: The shared part which is not changed with the external environment within the object of the enjoyment;
- External state: As the environment changes, the state that cannot be shared is the external state.
Because the enjoy meta-mode distinguishes between internal and external states, we can set different external states so that the same object can have some different characteristics, and the internal state is set to the same part. In our program design process, we may need a large number of fine-grained objects, if these objects in addition to a few parameters, the other parts are the same, this time we can use the enjoy meta-mode to greatly reduce the objects in the application. How do you use the enjoy meta model? Here we just need to move the different states of their smaller parts as arguments to the outside of the class instance, and then pass them over when the method is called. Here's a point: the internal state is stored inside the enjoy meta object, while the external state should be considered by the client.
comparing the mode of sharing and object pooling
Seeing the above features reminds us of the object pool pattern, indeed, there are a lot of similarities between the object pool pattern and the enjoy meta pattern, but they have a very important difference: the enjoy meta-mode typically gets an immutable instance, whereas objects obtained from the object pool schema are typically mutable. so use the enjoy meta-mode to avoid creating multiple objects that have the same state, create only one, and use that instance in different places in the application, whereas the resources in the object pool have different states from the perspective of use and each need to be individually controlled. But do not want to spend a certain resource area to create and destroy these resource objects frequently, after all, they all have the same initialization process.
In short, the enjoy meta mode is more prone to state immutability, while the object pool pattern is the variability of the state.
UML class Diagram
The UML class diagram for the enjoy meta-mode is as follows:
- Flyweight:
An abstract base class or interface for a metadata object;
- Concreteflyweight:
The specific object of the element of enjoyment;
- Unsharedconcreteflyweight:
Non-shared specific class of flyweight, indicating those who do not need to share the sub-class;
- Flyweightfactory:
Enjoy meta-factory, which manages the pool of objects for the sharing and creation of the privilege objects.
As a result, we can write the basic code of the enjoy meta-pattern:
Flyweight.class
publicinterface Flyweight { void operation();}
Concreteflyweight.class
publicclass ConcreteFlyweight implements Flyweight{ private String intrinsicState; publicConcreteFlyweight(String state) { intrinsicState = state; } @Override publicvoidoperation() { Log.e("Shawn""ConcreteFlyweight----" + intrinsicState); }}
Flyweightfactory.class
publicclass FlyweightFactory { privatenew HashMap<>(); publicgetFlyweight(String key) { Flyweight flyweight = mFlyweights.get(key); ifnull) { new ConcreteFlyweight(key); mFlyweights.put(key, flyweight); } return flyweight; }}
Test code
flyweight flyweight1 = Factory.getflyweight ( Span class= "hljs-string" > "a" ) Flyweight flyweight2 = Factory.getflyweight ( "B" ) Flyweight FLYWEIGHT3 = Factory.getflyweight ( "a" ) Log.e ( "Shawn" , "flyweight1==flyweight2:" + (flyweight1 = = flyweight2)) Log.e ( "Shawn" , "FLYWEIGHT1==FLYWEIGHT3:" + (flyweight1 = = FLYWEIGHT3)) break
Results
com.android.flyweightpattern E/Shawn: flyweight1==flyweight2 : falsecom.android.flyweightpattern E/Shawn: flyweight1==flyweight3 : true
It is obvious to see that the flyweight1 and FLYWEIGHT3 objects are the same object of enjoyment.
the enjoy meta-mode in Java
In Java, the most classic case of using the enjoy meta-pattern should be a string, string exists in a constant pool, that is, a string is defined after it is cached in the constant pool, when other places to use the same string, the cache is used directly, but not repeatedly created (this is The immutability of String: java/android design Mode Learning notes (11)-prototype mode).
For example, the following code:
StringnewString("abc");StringnewString("abc");String"abc";String"ab""c"//false//true
STR1 and STR2 are two different objects, this should be obvious, and STR3 and STR4 are all using the String pool, so they are the same object.
Example and source code
Let's take a graphic system, for example, to draw a circle of different colors:
Shape.class is used to define the basic behavior of a graph:
publicinterface Shape { void draw();}
An implementation subclass of the Circle.class shape, used to draw a circle:
publicclass Circle implements Shape{ String color; publicCircle(String color) { this.color = color; } @Override publicvoiddraw() { Log.e("Shawn""画了一个" + color +"的圆形"); }}
Shapefactory.class graphics to enjoy Meta factory class:
publicclass ShapeFactory { privatenew HashMap<>(); publicgetShape(String color) { Shape shape = shapes.get(color); ifnull) { new Circle(color); shapes.put(color, shape); } return shape; } publicintgetSize() { return shapes.size(); }}
Test code
Shape Shape1 = Factory. Getshape("Red");Shape1. Draw();Shape Shape2 = Factory. Getshape("Grey");Shape2. Draw();Shape Shape3 = Factory. Getshape("Green");Shape3. Draw();Shape Shape4 = Factory. Getshape("Red");Shape4. Draw();Shape Shape5 = Factory. Getshape("Grey");Shape5. Draw();Shape Shape6 = Factory. Getshape("Grey");Shape6. Draw();Log. E("Shawn","It's all drawn."+factory. GetSize()+"The color of the circle");
Last Run result
As you can see from the results, a graphic of the same color shared an object, creating only 3 objects in total.
Summary
The enjoy meta-mode implementation is relatively simple, but its role in some scenarios is indeed extremely important. It can greatly reduce the number and frequency of objects created by the application, reduce the use of program memory, enhance the performance of the program, but it also increases the complexity of the system, need to separate out the external state and internal state, the internal state is a constant shared part, stored in the share object inside, and the external state has the curing characteristics, Should be the responsibility of the client, should not change with the internal state changes, otherwise it will lead to logical confusion of the system.
Benefits of the meta-mode:
- Can greatly reduce the number of objects in the system;
- Enjoy meta mode because the external state is used externally, the outer state is relatively independent and does not affect the internal state, so the enjoy meta-mode allows the sharing meta-object to be shared in different environments.
The disadvantage of the meta mode:
- The application is somewhat more complicated by the need to differentiate the external state from the internal state of the meta-mode;
- In order for objects to be shared, the enjoy meta-mode requires the state of the object to be externally instantiated, while the read external state makes the run time longer.
discussion
As I look at the books and web materials, I see that some of the articles will define Messagepool in Android as the "meta" mode, but after comparing the object pool mode and the enjoy meta pattern, I would prefer to think of it as the object pool mode, because from the comparison described above, The object pool in Messagepool has an initialized size, and each time you obtain a Message object from Messagepool, you get an initial object in which the state needs to change according to the requirements, while the enjoy meta-pattern prefers to reuse objects with the same state. This object is focused on the application of each place where its state has the same, from this principle has been excluded is to enjoy the meta-model, but still a personal view, there is no great God guidance, greatly appreciated ~ ~ ~
Source Download
Https://github.com/zhaozepeng/Design-Patterns/tree/master/FlyweightPattern
References
Http://stackoverflow.com/questions/9322141/flyweight-vs-object-pool-patterns-when-is-each-useful
http://blog.csdn.net/jason0539/article/details/22908915
Https://en.wikipedia.org/wiki/Flyweight_pattern
Http://www.cnblogs.com/qianxudetianxia/archive/2011/08/10/2133659.html
http://blog.csdn.net/chenssy/article/details/11850107
Java/android Design Pattern Learning Note (---) enjoy meta mode