Design mode: Enjoy meta mode (Flyweight)

Source: Internet
Author: User

? Use shared technology to effectively support a large number of fine-grained objects. Also known as the "Fly volume pattern".
? In the Java language, the string type is the use of the enjoy meta mode. The string object is the final type, and the object cannot be changed once it is created. In Java, where string constants are present in a constant pool, Java ensures that a string constant has only one copy in the constant pool. Such as:

String"abc";String"abc";System.out.println(a==b);

? output: True. This means that both A and B references point to the same string constant "ABC" in the Constant pool. Such a design avoids the unnecessary amount of resource consumption generated when creating n many identical objects.

The????????????? To avoid the overhead of having the same content object in large numbers. The most common and intuitive kind of overhead is memory consumption. The key to sharing the shared meta object is to differentiate between the intrinsic state (the Internal State) and the outer states (External).
? An intrinsic state is stored inside the element of the object and is not changed as the environment changes. Therefore, a share can be intrinsic and shareable.
? A foreign State is changed with the change of the environment and cannot be shared. The outer state of the object must be saved by the client, and then passed in to the inside of the object when it is needed after the object is created. The external state can not affect the intrinsic state of the object of the enjoyment, they are independent of each other.
The "Enjoy meta" mode can be divided into simple and complex mode.

Simply enjoy meta mode

Included roles:

    1. abstract enjoy meta-role (Flyweight): An abstract interface is given to specify the methods that are required for all the specific privileges that a meta-role needs to be implemented.
    2. specific enjoy meta roles (concreteflyweight) : Implements the interface defined by the abstract-enjoy meta role. If there is an intrinsic state, you must be responsible for providing storage space for the intrinsic state.
    3. enjoy meta factory role (Flyweightfactory) : This role is responsible for creating and managing the rewards role. This orange must be guaranteed to be properly shared by the system. When a client object invokes an object, the enjoy Meta factory role checks to see if there is already an eligible object in the system. If it is already available, the meta-factory role should provide the existing one, and if the system does not have an appropriate element of the object, the enjoy meta-factory role should create a suitable object for the privilege.

To give a simple example
1 abstract enjoy meta role

publicinterface Flyweight{    publicvoidoperation(String state);}

2 Specific enjoy meta roles

publicclass ConcreteFlyweight implements Flyweight{    private String str;    publicConcreteFlyweight(String str)    {        this.str = str;    }    @Override    publicvoidoperation(String state)    {        System.out.println("内蕴状态:"+str);        System.out.println("外蕴状态:"+state);    }}

3 Enjoy meta factory role

 Public classflyweightfactory{Privatemap<string,concreteflyweight> flyweights =NewHashmap<string, concreteflyweight> (); PublicConcreteflyweightFactory(String str) {Concreteflyweight flyweight = flyweights.Get(str);if(NULL= = Flyweight) {flyweight =NewConcreteflyweight (str);        Flyweights.put (str, flyweight); }returnFlyweight } Public int getflyweightsize()    {returnFlyweights.size (); }}

4 test Code

Flyweightfactory factory = new Flyweightfactory ();Flyweight F1 = Factory. Factory("a");Flyweight F2 = Factory. Factory("B");Flyweight F3 = Factory. Factory("a");F1. Operation("A fly Weight");F2. Operation("b Fly Weight");F3. Operation("C Fly Weight");System. out. println(f1 = = F3);System. out. println(Factory. Getflyweightsize());

Output Result:

内蕴状态:a外蕴状态:a fly weight内蕴状态:b外蕴状态:b fly weight内蕴状态:a外蕴状态:c fly weighttrue2
Compound enjoy meta mode

? In the simple-to-enjoy meta-mode, all the objects are simply to enjoy the meta-object, that is, they can be directly shared, some simple to use the composition of the composite mode to compound, to form a compound to enjoy meta-objects. Such compound-sharing objects cannot be shared by themselves, but they can be decomposed into simple-to-enjoy meta-objects, while the latter can be shared.
? The included role

    1. Abstract enjoy meta-role (Flyweight): An abstract interface is given to specify the methods that are required for all the specific privileges that a meta-role needs to be implemented.
    2. Specific concreteflyweight: Implements the interface defined by the abstract privileges meta role. If there is an intrinsic state, you must be responsible for providing storage space for the intrinsic state.
    3. Compound enjoy meta-role (concretecompositeflyweight): Compound to enjoy the object that the orange represents is not shareable, but a composite object can be decomposed into a combination of objects that are inherently pure. The compound privilege role is also known as a non-shareable, shared meta object.
    4. Enjoy meta-factory role (Flyweightfactory): This role is responsible for creating and managing the rewards role. This orange must be guaranteed to be properly shared by the system. When a client object invokes an object, the enjoy Meta factory role checks to see if there is already an eligible object in the system. If it is already available, the meta-factory role should provide the existing one, and if the system does not have an appropriate element of the object, the enjoy meta-factory role should create a suitable object for the privilege.

Change the above example:
1 abstract enjoy meta role (IBID.)
2 Specific privilege roles (IBID.)
3 Composite enjoy meta role
The compound-sharing object is composed of a simple-to-enjoy meta-object, thus providing an aggregation management method such as add (). Because a composite object has different aggregation elements, these aggregation elements are added after the compound's object is created, which in itself means that the state of the compound's object is changed, so that the composite object cannot be shared.

 Public  class concretecompositeflyweight implements Flyweight{    Privatemap<string,flyweight> flyweights =NewHashmap<string, flyweight> (); Public void Add(String key, Flyweight fly)    {Flyweights.put (key, fly); }@Override     Public void Operation(String State) {Flyweight Fly =NULL; for(String S:flyweights.keyset ())            {fly = Flyweights.get (s);        Fly.operation (state); }    }}

The 4 enjoy meta-factory role provides two different methods for providing a simple-to-use meta-object, and another for providing a compound-sharing object.

 Public classflyweightcompositefactory{Privatemap<string,flyweight> flyweights =NewHashmap<string, flyweight> (); PublicFlyweightFactory(list<string> compositestates) {Concretecompositeflyweight Compositefly =NewConcretecompositeflyweight (); for(String s:compositestates) {Compositefly.add (s), This. Factory (s)); }returnCompositefly; } PublicFlyweightFactory(String s) {Flyweight fly = flyweights.Get(s);if(Fly = =NULL) {fly =NewConcreteflyweight (s);        Flyweights.put (S, fly); }returnFly }}

5 Test Code

list<string> list = new arraylist<string> ();List. Add("a");List. Add("B");List. Add("C");List. Add("a");List. Add("B");Flyweightcompositefactory factory = new Flyweightcompositefactory ();Flyweight F1 = Factory. Factory(list);Flyweight F2 = Factory. Factory(list);F1. Operation("Composite call");System. out. println("=======");System. out. println(whether the composite sharing mode can share objects:+ (F1 = = F2));String str ="a";Flyweight F3 = Factory. Factory(str);Flyweight F4 = Factory. Factory(str);System. out. println("Pure meta mode can share objects:"+ (F3 = = F4));

Operation Result:

内蕴状态:b外蕴状态:Composite Call内蕴状态:c外蕴状态:Composite Call内蕴状态:a外蕴状态:Composite Call=======复合享元模式是否可以共享对象:false单纯享元模式是否可以共享对象:true

? From the above example, it is known that an outer state of all the elements of a simple-to-enjoy element that conforms to the object of a privilege is equal to the outer state of the compound-sharing object. The intrinsic state of a simple-to-enjoy meta-object contained by a compound-sharing object is generally unequal. Compound-sharing objects are not shared. A simple-to-enjoy meta-object is shareable.

To give a more vivid example, such as go to a restaurant to eat, the menu only one, and each customer order is different, but there will certainly be a repetition, we use the above-mentioned mode of enjoyment to try to simulate the code situation:

Flyweightcompositefactory factory = new Flyweightcompositefactory ();list<string> menulist = Arrays. Aslist("Shredded pork with fish flavor","Kung Pao Chicken","Hang Pepper beef Tenderloin","Pan Fish","scrambled egg with tomato");Flyweight F1 = Factory. Factory(menulist. sublist(0,2));Flyweight F2 = Factory. Factory(menulist. sublist(2,3));F1. Operation("Customer1 's Menu");System. out. println("================");F2. Operation("Customer2 's Menu");

Code output:

内蕴状态:鱼香肉丝外蕴状态:customer1的菜单内蕴状态:宫保鸡丁外蕴状态:customer1的菜单================内蕴状态:杭椒牛柳外蕴状态:customer2的菜单

Pros and cons
Pros : Drastically reduce the number of objects in memory
Cons : The enjoy meta-mode makes the system more complex. In order for objects to be shared, some States need to be externally instantiated, which complicates the logic of the program. The enjoy meta-mode takes the state of the Meta object out of the way, while reading the external state makes the run time slightly longer.

Enjoy meta-mode in JDK
java.lang.integer#valueof (int)
Java.lang.boolean#valueof (Boolean)
Java.lang.byte#valueof (Byte)
Java.lang.character#valueof (Boolean)

Resources
1. "23 Design Patterns"
2. Design patterns in the "digital JDK"
3. The "Java and mode" of the model of the enjoyment of

Design mode: Enjoy meta mode (Flyweight)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.