Design pattern (one)--flyweight (enjoy meta mode)--Structural type

Source: Internet
Author: User
Tags abstract constant constructor garbage collection reserved stub

Author qq:1095737364 QQ Group: 123300273 Welcome to join.1. Pattern Definition:The enjoy meta mode is the structure mode of the object. The enjoy meta mode efficiently supports a large number of fine-grained objects in a shared manner.2. Mode features:The enjoy meta-mode is a design mode that takes system performance into account, and it can save memory space and improve the performance of the system by using the enjoy meta-mode.   When there are a large number of identical or similar objects in the system, the meta-mode is a better solution, which realizes the reuse of the same or similar fine-grained objects by sharing technology, thus saving the memory space and improving the system performance. Compared to other structural design patterns, the usage frequency is not too high, but as a "save memory, improve performance" as the starting point of the design pattern, it in the software development is still a certain degree of application to enjoy the Meta factory class, the function of the enjoy meta-factory is to provide a pool to store the enjoyment of meta-objects, When a user needs an object, it is first fetched from the pool of privileges, and if it does not exist in the pool, a new one is created to return to the user and the new object is saved in the pool of privileges.3. Usage Scenarios:1, if an application uses a large number of fine-grained objects, you can use the enjoy meta-mode to reduce the number of objects, 2, if the use of a large number of objects, these objects consume a lot of memory, you can use the enjoy meta-mode to reduce the number of objects, and save memory; 3 For example, by calculation, or from the outside, you can use the enjoy meta-mode to achieve the separation of internal state and external State; 4, these objects can be divided into many groups according to the intrinsic state, when the outer objects are removed from the object, each group of objects can be replaced by an object; 5, the system does not depend on these object identities, These objects are not distinguishable; 6, enjoy meta-mode is generally given to the local memory resources to save a solution, not suitable for distributed applications on the Internet, but enjoy the meta-model of the exclusive requirements of resource control, is a good choice;4. Mode implementation: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 the loss of memory.   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 does not vary depending on the environment.   Therefore, a share can have an intrinsic state and can be shared. 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 outer state can not affect the intrinsic state of the objects, they are independent of each other. The enjoy meta-mode can be divided into two forms: the simple-enjoy meta-mode and the compound-sharing model.(1) simple to enjoy meta modeIn the simple-to-enjoy mode, all the objects of the object can be shared.the roles involved in the simple-to-enjoy meta model are as follows[1] abstract enjoy meta (Flyweight) role:An abstract interface is given to specify the methods that are required to be implemented for all of the specific enjoyment meta-roles.

Public interface Flyweight {
    //A schematic method, the state of the parameter is the outside of the states public
    void operation (String);
}
[2] specific privileges (concreteflyweight) role: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.
public class Concreteflyweight implements Flyweight {
    private Character intrinsicstate = null;
    /**
     * constructor, intrinsic status passed in as parameter
     * @param State
     *
    /Public concreteflyweight (Character) {
        This.intrinsicstate = State;
    }    
    /**
     * External state as a parameter in the method, change the behavior of the method,
     * But does not change the intrinsic state of the object.
     *
    /@Override public
    void operation (String state) {
        //TODO auto-generated method stub
        SYSTEM.OUT.PRINTLN ("intrinsic state =" + this.intrinsicstate);
        SYSTEM.OUT.PRINTLN ("Extrinsic state =" + state);
    }
}
The concreteflyweight has an intrinsic state, in this case the Intrinsicstate attribute of a character type is represented, and its value should be given when the element object is created.   All the intrinsic states are not changed after the object is created. If an object has an external state, all external states must be stored on the client, and the client is passed in with the object of the privilege when the element is used. There is only one external state, and the operation () method's parameter state is an external incoming foreign. [3] enjoy meta Factory (flyweightfactory) role:This role is responsible for creating and managing the sharing meta role. This role must ensure that the sharing meta-object can 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.
public class Flyweightfactory {
    private map<character,flyweight> files = new Hashmap<character,flyweight > ();    
    Public Flyweight Factory (Character state) {
        //First Find object from cache
        Flyweight fly = Files.get (state);
        if (fly = = null) {
            //Create a new Flyweight object if the object does not exist
            fly = new Concreteflyweight (state);
            Add this new flyweight object to the cache
            Files.put (state, fly);
        }
        return fly;
    }
}
Enjoy the meta-factory role class, it must be noted that the client cannot instantiate a specific class of classes directly, but must pass a factory object, using a factory () method to get the object of the privilege.   In general, there is only one in the entire system for the enjoy Meta factory object, so you can also use singleton mode. When the client needs to simply enjoy the meta-object, it is necessary to call the factory () method of the Meta factory and pass in the intrinsic state of the desired simple-to-enjoy meta-object, and the factory method produces the desired object. [4] client class
public class Client {public
    static void Main (string[] args) {
        //TODO auto-generated method stub
        FLYWEIGHTFAC Tory factory = new flyweightfactory ();
        Flyweight fly = factory.factory (new Character (' a '));
        Fly.operation ("First call");        
        Fly = Factory.factory (new Character (' B '));
        Fly.operation ("Second call");        
        Fly = Factory.factory (new Character (' a '));
        Fly.operation ("Third call");
    }
}
Although the client has requested three of the objects, only two are actually created, which is the meaning of sharing. The results of the operation are as follows: (2) compound to enjoy meta-modeIn the simple-to-enjoy meta-mode, all the objects of the object are simply to enjoy the meta-object, which means they can be shared directly. There is also a more complex situation, the use of a few simple-to-enjoy composite model 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 roles involved in the compound-sharing role are as follows: [1] abstract enjoy meta (Flyweight) role:An abstract interface is given to specify the methods that are required to be implemented for all of the specific enjoyment meta-roles.
Public interface Flyweight {
    //A schematic method, the state of the parameter is the outside of the states public
    void operation (String);
}
[2] specific privileges (concreteflyweight) role: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.
public class Concreteflyweight implements Flyweight {
    private Character intrinsicstate = null;
    /**
     * constructor, intrinsic status passed in as parameter
     * @param State
     *
    /Public concreteflyweight (Character) {
        This.intrinsicstate = State;
    }
    /**
     * External state as a parameter in the method, change the behavior of the method,
     * But does not change the intrinsic state of the object.
     *
    /@Override public
    void operation (String state) {
        //TODO auto-generated method stub
        SYSTEM.OUT.PRINTLN ("intrinsic state =" + this.intrinsicstate);
        SYSTEM.OUT.PRINTLN ("Extrinsic state =" + state);
    }
}
A compound-sharing object is composed of a simple-to-enjoy meta-object, so it provides 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. [3] Compound (concretecompositeflyweight) role:The object represented by the compound privilege role is not shareable, but a composite object can be decomposed into a combination of multiple, simple-to-enjoy meta-objects. The compound privilege role is also known as a non-shareable, shared meta object.
public class Concretecompositeflyweight implements Flyweight {    
    private map<character,flyweight> files = new Hashmap<character,flyweight> ();
    /**
     * Add a new Simple object to the aggregation in */
     public
    void Add (Character key, Flyweight fly) {
        files.put (key,fly);
    }
    /**
     * The outer state is passed as a parameter in the method *
    /@Override public
    void operation (String states) {
        Flyweight fly = null;< C14/>for (Object o:files.keyset ()) {
            fly = Files.get (o);
            Fly.operation (state);}}}
The compound-enjoy meta-role implements the interface defined by the abstract-enjoy meta-role, which is the operation () method, which has a parameter that represents the outer state of the composite object. The outer state of all the primitive elements of a compound-sharing object is equal to the outer state of the compound-sharing object, while the intrinsic state of the pure-object contained in a compound-sharing object is generally unequal, otherwise there is no use value. [4] enjoy meta Factory (flyweightfactory) role:    This role is responsible for creating and managing the sharing meta role. This role must ensure that the sharing meta-object can 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.
public class Flyweightfactory {
    private map<character,flyweight> files = new Hashmap<character,flyweight > ();
    /**
     * Compound to enjoy meta factory method *
    /Public Flyweight factory (list<character> compositestate) {
        Concretecompositeflyweight compositefly = new Concretecompositeflyweight ();
        
        for (Character state:compositestate) {
            Compositefly.add (the State,this.factory (state));
        }
        
        return compositefly;
    }
    /**
     * Simple to enjoy meta factory method *
    /Public Flyweight factory (Character state) {
        //First Find object from cache
        Flyweight fly = Files.get (state);
        if (fly = = null) {
            //Create a new Flyweight object if the object does not exist
            fly = new Concreteflyweight (state);
            Add this new flyweight object to the cache
            Files.put (state, fly);
        }
        return fly;
    }
}
The enjoy Meta factory role provides two different methods, one for providing a simple-to-use meta-object, and the other for providing a compound-sharing object. [5] Client role
public class Client {public
    static void Main (string[] args) {
        list<character> compositestate = new Arraylis T<character> ();
        Compositestate.add (' a ');
        Compositestate.add (' B ');
        Compositestate.add (' C ');
        Compositestate.add (' a ');
        Compositestate.add (' B ');        
        Flyweightfactory flyfactory = new Flyweightfactory ();
        Flyweight compositeFly1 = flyfactory.factory (compositestate);
        Flyweight compositeFly2 = flyfactory.factory (compositestate);
        Compositefly1.operation ("Composite call");       
        System.out.println ("---------------------------------");        
        SYSTEM.OUT.PRINTLN ("Composite sharing mode can share objects:" + (compositeFly1 = = compositeFly2));        
        Character state = ' a ';
        Flyweight fly1 = flyfactory.factory (state);
        Flyweight fly2 = flyfactory.factory (state);
        System.out.println ("Pure meta mode can share objects:" + (fly1 = = Fly2));}
}
The results of the operation are as follows:From the running result, it can be seen that the outer state of all the elements of the pure element object of a compound-object is equal to the outer state of the compound-sharing object.      The Sinotrans status equals composite call. From the running results, it can be seen that the intrinsic state of the simple-to-enjoy meta-objects contained in a compound-sharing object is generally unequal.      That is, the intrinsic states are B, C, a respectively. As you can see from the running results, the compound-sharing object cannot be shared.      Objects that were created two times by factory, even with the same object compositestate, are not the same object. From the running results, it can be seen that the simple-to-enjoy meta-objects can be shared.     objects created with the same object state through the factory two times are the same object. The difference between the simple-to-enjoy meta-mode and the compound-sharing model: The compound-enjoy meta-mode has more than one Concretecompositeflyweight class, and this class is not shareable, so the compound of the meta-object itself cannot be shared, but they can be decomposed into a simple to enjoy the meta-object, The simple-to-enjoy meta-object can be shared. 5. Advantages and Disadvantages: (1) Benefits of the meta-mode[1] greatly reduce the creation of objects, reduce the system's memory, so as to improve efficiency. [2] can share the same or similar fine-grained objects, save system resources, provide system performance, while reducing the cost of object creation and garbage collection. [3] The external state in the enjoy meta-mode is relatively independent, allowing objects to be reused in different environments (shared objects can be adapted to different external environments) without affecting the internal state. (2) The disadvantage of sharing meta-mode[1] To improve the complexity of the system, the need to separate out the external state and internal state, and the intrinsic nature of the external state, should not be changed with the internal state of the change, otherwise it will cause chaos in the system. [2] The external state is saved by the client, and the shared object may have a larger cost of reading the external state. [3] The enjoy meta-mode requires separating the internal state from the external state, which complicates the logic of the program and also increases the cost of state maintenance and complicates the program logic. [4] The enjoy meta-mode will allow the state of the meta-object to be instantiated, while reading the external state makes the run time slightly longer. 6. Model in-depth explanationThe enjoy meta-mode is a design mode that takes system performance into account, and it can save memory space and improve the performance of the system by using the enjoy meta-mode. (1) Change and constantThe main point of the design of the model is to separate the state of an object into the intrinsic state and the outer state, the intrinsic state is invariable, and the outer state is variable. Then, by sharing the unchanging parts, we achieve the goal of reducing the number of objects and saving memory.     When the object needs to be used, the external state can be passed from outside to the shared object, and the shared object will use its intrinsic state and these outer states when the function is processed. In fact, separation and invariant is one of the most basic software design methods, such as reserved interface, why in this place to reserve interface, a common reason is that there is a change, it may need to expand in the future, or change the existing implementation, so the reserved interface as "pluggable guarantee." (2) Sharing and not sharingIn the enjoy meta-mode, enjoy the meta-object has shared and not share the points, that is, the simple to enjoy the meta and compound to enjoy the element, is usually shared by the leaf object, the general share of the part is composed of shared parts, because all the fine-grained leaf objects have been cached, so there is no need to cache tree nodes, that is , the compound privilege does not need to be shared. (3) instance poolIn the enjoy meta-mode, in order to create and manage shared portions of the share, the introduction of the enjoy meta-factory, the enjoy meta-factory typically contains the instance pool of the object, the enjoyment of the meta-object is cached in this instance pool.   A simple introduction to the knowledge of an instance pool, the so-called instance pool, refers to the program that caches and manages object instances, typically the instance pool provides the environment in which the object instance is run and controls the life cycle of the object instance. Industrial-level instance pool implementation has two most basic difficulties, one is the dynamic control of the number of instances, one is the dynamic allocation of instances to provide for external use.   These are the algorithms that need to be guaranteed. If there are 3 instances in the instance pool, but the client requests very much, some busy, then the management program of the instance pool should be judged out, in the end a few instances to meet the current customer needs, the ideal situation is just good, is to meet the needs of the application, and will not cause the waste of object instances,   If the 5 instances are judged to be good, then the management program of the instance pool should be able to dynamically create 2 new instances. This run for a period of time, the client's request is reduced, this time the management process of the instance pool should be dynamic judgment, how many instances are the best, more obvious waste of resources, if the judge only need 1 instances to be able to, then the instance Pool management program should destroy the extra 4 instances to release resources.   This is the number of dynamic control instances. For the dynamic allocation instance, also explain, if there are 3 instances in the instance pool, this time a new request, in the end to dispatch which instance to execute the client's request, if there is idle instance, that is it, if there is no idle instance, is to create a new instance, or wait for the running instance, When it runs out, deal with the request.   How to dispatch, also need algorithm to protect. Return to the enjoy meta-mode, the instance pool in the Meta factory is not so complicated, because the shared object is basically an instance, generally does not appear to have multiple instances of the same enjoy meta object, so you do not have to consider the ability to dynamically create and destroy the instance of the object of the privilege;   There is no problem of dynamic scheduling, anyway it is. This is mainly because the object encapsulation is mostly the internal state of the objects, these states are usually constant, there is an instance of enough, do not need to dynamically control the life cycle, and do not need dynamic scheduling, it only need to do a cache, does not rise to the real instance pool of the height. 7. Application Examples (1) String type in JavaIn the Java language, the string type is the use of the enjoy meta pattern. 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. String a= "abc", where "abc" is a string constant.
public class Test {public
    static void Main (string[] args) {        
        String a = "abc";
        String B = "abc";
        System.out.println (a==b);        
    }
}
The result in the above example is: true, which means that both A and B two 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.

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.