Java Design Pattern Learning record-Enjoy meta mode

Source: Internet
Author: User
Objective

The enjoy meta-mode is also a structured model, which is the last of a description of the structural pattern (because the proxy mode was written earlier). The enjoy meta mode takes a share to avoid the overhead of having the same content object in large numbers. The most common and intuitive kind of overhead is memory loss.

Enjoy meta-mode definition

Enjoy meta-mode refers to the use of shared technology to support the reuse of a large number of fine-grained objects. the system uses only a small number of objects , and these objects are very similar, the state changes very small, you can achieve multiple reuse of objects. Because the enjoy meta mode requires that the object that can be shared must be a fine-grained object, it is also known as lightweight mode, which is an object-structured pattern.

Example

Coffee problem, there are several flavors of coffee in a coffee shop, for example: Latte, mocha, cappuccino and so on. Recently the store is engaged in promotional activities, one noon can sell hundreds of cups of coffee, then the taste of coffee is a shared element. The following code is used to implement this example.

Defining the Order Interface

/***/Publicinterface  Order    {// Sell Coffee    void  sell ();}

Specific order Fulfillment

 Public class Implements Order {    // coffee taste public      String flavor;      Public Coffeeorder (String flavor) {        this. Flavor= flavor;    }    @Override    publicvoid  sell () {        System.out.println ("sold a copy" +flavor + "The coffee. ");    }}

Order Factory Class

ImportCom.google.common.collect.Maps;ImportJava.util.Map;Importjava.util.Objects;/*** Order factory class*/ Public classCoffeeorderfactory {Private StaticMap<string,order> COF =Maps.newhashmap (); /*** Get Order *@paramFlavor Taste *@return     */     Public StaticOrder GetOrder (String flavor) {Order Order=cof.get (flavor); if(Objects.isnull (order)) {Order=NewCoffeeorder (flavor);        Cof.put (Flavor,order); }        returnorder; }    /*** Get the number of objects that are ultimately created *@return     */     Public Static intGetSize () {returncof.size (); }}

Test class

Importorg.assertj.core.util.Lists;Importjava.util.List;/*** Test to buy coffee*/ Public classMyTest { Public Static voidMain (string[] args) {Buycoffee ("Latte"); Buycoffee (Cappuccino); Buycoffee ("Mocha"); Buycoffee ("Latte"); Buycoffee ("Latte"); Buycoffee ("Latte"); Buycoffee (Cappuccino); Buycoffee (Cappuccino); Buycoffee (Cappuccino); Buycoffee ("Mocha"); Buycoffee ("Mocha"); Buycoffee ("Mocha"); //print out the coffee for saleCoffeeorderlist.stream (). ForEach (Order::sell); System.out.println ("A total of selling to" +coffeeorderlist.size () + "Cup OF coffee! "); System.out.println ("A total of" +coffeeorderfactory.getsize () + "Java objects have been generated! "); }    //Order List     Public StaticList<order> coffeeorderlist =lists.newarraylist (); /*** Buy Coffee *@paramFlavor Flavors*/     Public Static voidBuycoffee (String flavor) {Coffeeorderlist.add (Coffeeorderfactory.getorder (flavor)); }}

Run results

Sold a latte of coffee. Sold a cappuccino for a coffee. Sold a mocha cup of coffee. Sold a latte of coffee. Sold a latte of coffee. Sold a latte of coffee. Sold a cappuccino for a coffee. Sold a cappuccino for a coffee. Sold a cappuccino for a coffee. Sold a mocha cup of coffee. Sold a mocha cup of coffee. Sold a mocha cup of coffee. Sell 12 cups of coffee altogether! A total of 3 Java objects were generated!

From the above results can be seen, although the sale of 12 cups of coffee, but the final taste of the object only 3, because the coffee taste only when the first time the use of the creation, the back of the direct use will not be created.

Analysis of the meta-mode of enjoyment

The following is to analyze the structure of the enjoy meta-mode, the structure is as follows:

The roles involved in the enjoy meta-mode are abstract-enjoy meta-roles, specific-to-the-element roles, compound-enjoy meta-roles, the enjoy meta-factory role, and client roles. Specify the following:

    • abstract enjoy meta-role (FlyWeight): This role is the parent of all the specific classes of the class, specifying the public interfaces or abstract classes that need to be implemented for these classes. The order interface in the example above is the representative of this role.
    • specific Concreteflyweight: Implements the interface defined by the abstract-privileges meta-role. Sometimes the specific enjoy meta role is called a purely specific to the role of the meta, because the compound of the role of the meta-privilege is composed of the simple and specific to the meta-role. The Coffeeorder in the above example is the representative of this role.
    • Compound unsharableflyweight Role: the objects represented by the compound-enjoy meta-role are not shareable, but a composite-object can be decomposed into multiple combinations of objects that are inherently pure. A composite object is also known as a non-shareable object. This role is seldom used.
    • enjoy meta-factory role (Flyweightfactory): Responsible for creating and managing the rewards role. This role must ensure that the sharing meta-object can be properly shared by the system. When a client object requests an object for a privilege, the enjoy meta-factory role needs to check if there is already an eligible object in the system, and if it already has a privilege, it should provide the existing one, and if there is not an appropriate element of the object in the system, The enjoy meta-factory role should create a new and appropriate sharing object. The coffeeorderfactory in the above example is the representative of this role.
    • Client Role: This role invokes the enjoy meta-factory role to use the specific privilege role.
Enjoy the meta-model summary of the simple-to-enjoy meta-mode and compound-sharing model

The standard enjoy meta-mode contains both the object and the non-exclusive object, but in the actual use of the process we will use the specific two special forms of the enjoyment of meta-mode: Simple to enjoy the meta-model and the compound to enjoy meta-mode.

The simple-to-enjoy meta-mode means that all the specific object objects are shareable and do not include non-exclusive meta-objects.

Compound enjoy meta-mode refers to the use of some simple-to-enjoy meta-object combination mode, but also to form a combination of the object, so that the compound can not be shared, but it could be decomposed into simple to enjoy the meta-object, decomposition can be shared.

Benefits of the Enjoy meta model

1, can greatly reduce the number of objects in memory, so that the same or similar objects in memory only one copy, which can save system resources, improve system performance.

2. The external state of the enjoy meta-mode is relatively independent, and does not affect its internal state, so that the enjoyment meta-object can be shared in different environments.

Disadvantages of the enjoy meta model

1, the enjoyment of meta-mode makes the system become complex, need to separate the internal state and external state, which makes the logic of the program complicated.

2, in order to make the object can be shared, the enjoy meta-mode needs to be a part of the state of the object to be external, and read the external state will make the running time longer.

Applicable scenarios

A system has a large number of identical or similar objects, resulting in a large amount of memory consumption.

Most of the state of an object can be externally passed in to an object.

When you use the enjoy meta-mode, you need to maintain a pool of privileges that stores the metadata of the objects, which requires a certain amount of system resources, so it should be worthwhile to use the enjoy meta-mode when you need to reuse the object multiple times.

Extended

In the JDK there are examples of the use of the module, the most common is that we use the string class, we all know that the string class is final decorated, so will not be inherited, each change will generate a new string, which makes up a bit of memory. So if a string is written directly, when the same string is written back, it will automatically go to the heap (more than JDK7) to see if the string already exists, and if it does exist, it will be used directly if it does not exist at this time to open a space in the heap to store the string.

For example, the following example:

        String teststr = "Enjoy meta mode";         = "Enjoy meta mode";         = = teststring);        System.out.println (Teststr.equals (teststring));    

Operation Result:

true true


To learn more about design patterns, see the Java Design Patterns Learning record-gof design pattern Overview.

Interview face to suspect life, continue to refuel it!

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.