Design mode (12) Enjoy meta mode (Flyweight pattern)

Source: Internet
Author: User

First, Introduction

In the software development process, if we need to re-use an object, if we repeatedly use new to create this object, so that we in memory need to apply for memory space more than once, so that there may be more memory usage, the problem is very serious, However, the meta-mode can solve this problem, the following is a detailed look at how to solve the problem of the meta-mode.

second, enjoy the meta-model of the detailed introduction

In front of said, to enjoy the meta-mode can solve the above problem, before the introduction of the mode of sharing, let us first to analyze the next if you solve the above problem, the above problem is to repeat the creation of the same object, if let us solve this problem will certainly think: " since all are the same object, Can you just create an object and then the next time you need to create the object, let it just use the object you've already created, "that is--let an object share." Yes, this is also the essence of the realization of the meta-mode .

2.1 Definitions

After introducing the essence of the enjoy meta model, let's take a look at the formal definition of the meta-mode:

Enjoy meta mode--using shared technology to effectively support a large number of fine-grained objects. The enjoy meta-mode avoids the overhead of a lot of similar classes, and if you need to generate a lot of fine-grained class instances to represent the data in software development, if these instances are essentially the same except for a few parameters, you can use the enjoy meta-mode to drastically reduce the number of classes that need to be instantiated. If these parameters (referring to different parameters of these class instances) can be moved outside the class instance, they are passed in when the method is called, so that the number of individual instances can be drastically reduced by sharing. (This is also the main implementation of the meta-mode), however, we refer to the outside of the class instance as the external state of the object, and the inside of the object is defined as the internal state.

The definition of the internal state and external state of the specific object is:

Internal state:

Shared parts that are inside of the enjoyment meta object and do not change as the environment changes

External state:

A state that changes with the environment and cannot be shared.

2.2 Enjoy meta-mode implementation


After analysis of the realization of the model of the enjoyment of meta-mode, I believe that the realization of the mode of enjoyment is not a problem, the following with a century of application to achieve the next-to-enjoy meta-mode. This example is: A text editor will appear a lot of literal, using the use of the meta-mode to implement the text editor, will be each literal into a single object of enjoyment. The internal state of the enjoy meta object is this literal, and other information such as the position of the letter in the text and the font style is its external state. Here is the example to implement the following meta-mode, the implementation code is as follows:

    /// <summary>    ///Client Calls/// </summary>    classClient {Static voidMain (string[] args) {            //define external states, such as the location of letters            intExternalstate =Ten; //initialize the enjoy meta factoryFlyweightfactory factory =Newflyweightfactory (); //determine if the letter A has been created, and if it has been created, use the object created directlyFlyweight FA = Factory. Getflyweight ("A"); if(FA! =NULL)            {                //to call parameters for method invocation of an external state as a privilege objectFa. Operation (--externalstate); }            //determine if the letter B has been createdFlyweight fb = Factory. Getflyweight ("B"); if(FB! =NULL) {fb. Operation (--externalstate); }            //determine if the letter C has been createdFlyweight FC = Factory. Getflyweight ("C"); if(FC! =NULL) {FC. Operation (--externalstate); }            //determine if the letter D has been createdFlyweight fd= Factory. Getflyweight ("D"); if(FD! =NULL) {fd. Operation (--externalstate); }            Else{Console.WriteLine ("string d does not exist in the resident pool"); //At this point , you need to create an object and put it in the resident poolConcreteflyweight d =NewConcreteflyweight ("D"); FACTORY.FLYWEIGHTS.ADD ("D", D);        } console.read (); }    }    /// <summary>    ///enjoy meta-factory, responsible for creating and managing the Sharing object/// </summary>     Public classFlyweightfactory {//It is best to use the generic dictionary<string,flyweighy>//Public dictionary<string, flyweight> flyweights = new dictionary<string, flyweight> ();         PublicHashtable flyweights =NewHashtable ();  Publicflyweightfactory () {flyweights. ADD ("A",NewConcreteflyweight ("A")); Flyweights. ADD ("B",NewConcreteflyweight ("B")); Flyweights. ADD ("C",NewConcreteflyweight ("C")); }         PublicFlyweight Getflyweight (stringkey) {//better to achieve the following//Flyweight Flyweight = Flyweights[key] as Flyweight; //if (flyweight = = null)//{            //Console.WriteLine ("String not present in the resident pool" + key); //flyweight = new Concreteflyweight (key); //}            //return flyweight;returnFlyweights[key] asFlyweight; }    }    /// <summary>    ///abstract enjoy meta-class, providing a method for the specific class of enjoyment/// </summary>     Public Abstract classFlyweight { Public Abstract voidOperation (intextrinsicstate); }    //A specific object of enjoyment, so that we do not design each letter as a separate class, but as the internal state of the shared letter as the object of enjoyment     Public classConcreteflyweight:flyweight {//Internal State        Private stringintrinsicstate; //constructor Function         PublicConcreteflyweight (stringinnerstate) {             This. intrinsicstate =innerstate; }        /// <summary>        ///An instance method of the class of enjoyment/// </summary>        /// <param name= "Extrinsicstate" >External State</param>         Public Override voidOperation (intextrinsicstate) {Console.WriteLine ("concrete Implementation class: Intrinsicstate {0}, extrinsicstate {1}", Intrinsicstate, extrinsicstate); }    }

In the implementation of the module, we did not design a fine-grained class instance as a separate class, but instead put it in the internal definition of the shared class as the internal state of the shared object, and the explanatory notes are all there, so you can refer to the annotations to further understand the element pattern.

2.3 Class diagram of the enjoy meta-mode

After reading the realization of the meta-mode, in order to help you understand the relationship between the various categories in the meta-mode, the following shows the class diagram in the implementation code as follows:

In, there are several roles involved:

abstract enjoy meta-role (Flyweight): This role is the base class for all the specific classes of the classes that specify the public interfaces that need to be implemented. Operations that require an external state can be passed in as arguments by calling the method.

specific Concreteflyweight: Implements the interface defined by the abstract-privileges meta-role. If there is an internal state, it can be defined inside the class.

enjoy the meta-factory role (Flyweightfactory): This role is complex to create and manage the enjoy meta role. This role must ensure that the shared meta-object can be properly sharable by the system, and 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, and if it already exists, the enjoy meta-factory role provides the existing share object. If the system does not have an eligible metadata object, the enjoy meta-factory role should create an appropriate privilege object.

Client Role: This role needs to store the external state of all the privilege objects.

Note: The above implementation is only a simple to enjoy the meta-mode, but also a composite of the mode of sharing, because the complex to enjoy the meta-mode is more complicated, here is not to give the implementation.

third, the advantages and disadvantages of the meta model

After analyzing the implementation of the enjoy meta pattern, let's continue to analyze the pros and cons of the following meta-mode:

Advantages:

1, reduce the number of objects in the system, thus reducing the system of fine-grained objects to the memory of the pressure.

Disadvantages:

1, in order to make the object can be shared, some States need to be externally, which makes the logic of the program more complex, complicate the system.
2, the enjoy meta-mode will take the state of the Meta object out of the way, while reading the external state makes the run time slightly longer.


Iv. use of the scene


Consider using the enjoy meta-mode when all of the following conditions are met:

1, there are a large number of objects in a system;
2, these objects consume a lot of memory;
3, most of the states in these objects can be externally
4, these objects can be divided into many groups according to the internal state, when the external objects are removed from the object, each group can use only one object instead
5, the software system does not rely on the identity of these objects,


The system that satisfies the above conditions can use the enjoy meta mode. However, using the enjoy meta-mode requires the additional maintenance of a table of all the shares that the record subsystem already has, which also consumes resources, so it should be worthwhile to use the enjoy meta-mode when there are enough shared meta-instances to share.

Note: in. NET class library, the implementation of the string class uses the enjoy meta pattern, more content can refer to the introduction of the string dwell pool, but also can refer to this blog in-depth understanding. The design of string class in net--http://www.cnblogs.com/artech/archive/2010/11/25/internedstring.html

V. Summary
Here, the introduction of the meta-mode is over, and the enjoy meta-mode is mainly used to solve the problem of memory overhead caused by a large number of fine-grained objects, which is not commonly used in actual development, and can be used as a means to improve the performance of the underlying .

The above content excerpt from: http://learninghard.blog.51cto.com/6146675/1315781

Extended reading: Flyweight Pattern

Special topic in design mode (Learninghard)

Special topic in design mode (Lu Zhenyu)

Design mode (12) Enjoy meta mode (Flyweight pattern)

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.