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.
One, enjoy meta (Flyweight) mode
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.
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: The shared part that is inside of the enjoyment meta object and does not change as the environment changes
External state: A state that changes with the environment and cannot be shared.
Second, enjoy the meta-model of the class diagram
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 realization of the mode of enjoying yuan
Below is a practical application to achieve the next-to-the-element model. 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:
usingSystem;usingSystem.Collections;/// <summary>///Client Calls/// </summary>classclient{Static voidMain (string[] args) { //define external states, such as the location of letters intExternalstate =Ten; //initialize the enjoy meta factory varFactory =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 pool varD =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 ReadOnly string_intrinsicstate; //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.
Iv. use of the scene
Consider using the enjoy meta-mode when all of the following conditions are met:
- There are a large number of objects in a system;
- These objects consume a lot of memory;
- Most of the states in these objects can be externally
- These objects can be divided into groups according to their internal state, and when the external objects are removed from the object, each group can use just one object instead
- Software systems do not rely on the identities 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 the string class in net--proving the string residency mechanism through the Memory analysis tool
The advantages and disadvantages of the meta-mode of enjoyment
Advantages:
- Reduces the number of objects in the system, thus reducing the pressure on memory caused by fine-grained objects in the system.
Disadvantages:
- In order for objects to be shared, some States need to be externally instantiated, which makes the logic of the program more complex and complicates the system.
- 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.
Vi. 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 .
C # design mode-Enjoy meta mode