Flyweight mode details-design mode (9)

Source: Internet
Author: User

Flyweight mode causes:

creating objects is the most common operation in an object-oriented system design implementation. There is a problem here: If an application uses too many objects, it can cause significant storage overhead. Especially for a large number of lightweight (fine-grained) objects, such as in the design process of the document editor, if we create an object for the absence of letters, the system may waste storage overhead due to a large number of objects. For example, a letter "a" appears in the document 100,000 times, and in fact we can let the 10,000 letter "a" share an object, of course, because the letter "a" may have different display effect in different locations (such as font and size, etc.), in this case we can divide the state of the object into " External state "and" internal state ", the state can be shared (unchanged) stored in the object as an internal state, and external objects (such as the above mentioned font, size, etc.) we can at the appropriate time to the external object most parameters to the object (for example, when displayed, the font, size and other information passed to the object).

flyweight enjoy meta-mode function:

Flyweight mode is a mode to improve the efficiency and performance of the program, which will greatly speed up the operation of the program. There are many applications: for example, if you want to read a series of strings from a database, many of which are duplicates, then we can store these strings in the flyweight pool. is to create a primitive model, and then with different situations and environments, and then produce a specific model of each characteristic, it is obvious that here need to produce different new objects, so flyweight pattern often appear Factory mode . The internal state of the Flyweight is shared, and Flyweight factory is responsible for maintaining a flyweightpool (pattern Pool) object that holds the internal state.

Flyweight usage scenarios for the enjoy meta mode:

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

(1). A system has a large number of objects.

(2). These objects consume a lot of memory.

(3). Most of the states of these objects can be externally instantiated.

(4). These objects can be divided into many groups according to their intrinsic state, and each group can be replaced with only one object when the outer objects are removed from the object.

(5). The software system does not depend on the identities of these objects, in other words, the objects can be non-distinguishable.

Systems that meet these conditions can use the enjoy meta object.

Finally, using the enjoy meta-mode requires maintaining a table that records all the elements that the system already has, which consumes resources. Therefore, it should be worthwhile to use the enjoy meta-mode when there are enough shared meta instances available for sharing.

simple flyweight enjoy meta mode mode typical UML structure is shown in Figure 1:

Simple flyweight to enjoy meta-mode abstract base classes and interfaces:

Abstract enjoy meta (Flyweight) Role: This role is a superclass of all the specific classes of the classes that specify the public interfaces that need to be implemented. Operations that require the External state can be passed in as arguments by invoking a commercial method.

Specific Concreteflyweight role: implements the interface defined by the abstract-privilege meta-role. If there is an intrinsic state, you must be responsible for providing storage space for the intrinsic state. The intrinsic state of a shared meta object must be independent of the environment in which the object is located, so that the object of the enjoyment can share within the system.

Enjoy meta-factory (flyweightfactory) Role: This role is 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 invokes an object, the enjoy Meta factory role checks to see if there is already a compound requirement 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.

Client role: This role needs to maintain a reference to all of the enjoyment meta-objects. This role needs to store the external state of all the objects in its own memory.

The typical sample code for the simple flyweight -to-enjoy model is as follows:

Using system;using system.collections;//to enjoy Meta factory class flyweightfactory{//domain private Hashtable flyweights = new Hashtable () ;//Constructor public flyweightfactory () {flyweights. ADD ("X", New Concreteflyweight ()); flyweights. ADD ("Y", New Concreteflyweight ()); flyweights. ADD ("Z", New Concreteflyweight ());} Method public Flyweight Getflyweight (string key) {return ((Flyweight) flyweights[key]);}} Lightweight player abstract class flyweight{//method abstract public void operation (int extrinsicstate);} The specific classes class Concreteflyweight:flyweight{private string intrinsicstate = "A";//method override public void operation (int ex Trinsicstate) {Console.WriteLine ("Concreteflyweight:intrinsicstate {0}, extrinsicstate {1}", Intrinsicstate, extrinsicstate);}} public class Client{public static void Main (string[] args) {//arbitrary state int extrinsicstate = 22; Flyweightfactory f = new flyweightfactory ();//use different lightweight player instances Flyweight FX = F.getflyweight ("X"); FX. Operation (--extrinsicstate); Flyweight fy = f.getflyweight ("Y"), FY. Operation (--extrinsicstate); FlyweightFZ = F.getflyweight ("Z"); FZ. Operation (--extrinsicstate);}}
Composite Flyweight The typical UML structure is shown in Figure 2:

Compound flyweight the abstract base class and interface of the meta-mode:

Abstract enjoy meta role: this role is a superclass of all the specific classes of the class, specifying the public interfaces that need to be implemented for these classes. Operations that require the External state can be passed in through the parameters of the method. The interface of the abstract element makes it possible, but does not force the subclass to share, so not all of the objects are shareable.

Specific Concreteflyweight role: implements the interface defined by the abstract-privilege meta-role. If there is an intrinsic state, you must be responsible for providing storage space for the intrinsic state. The intrinsic state of a shared meta object must be independent of the environment in which the object is located, so that the enjoyment meta-object can share within the system. Sometimes the specific enjoy meta-role is also called the simple specific enjoy meta role, because the compound to enjoy the meta-role is composed of simple and specific to the meta-role through the composite.

Compound Unsharableflyweight Role: the objects represented by the compound-enjoy meta-role are 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 object of enjoyment.

Enjoy meta-factory (Flyweightfactoiy) Role: This role is 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 to see if there is an eligible object in the system, and if it does, 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.

Client role: This role also needs to store the external state of all the objects in its own.

Example 1: an example of a coffee

in this coffee stand (coffeestall) used in the system, there is a series of coffee "flavor (Flavor)." Guests go to the stalls to buy coffee, all the coffee is on the table, guests can get their own coffee and leave the stall. Coffee has an intrinsic state, that is, the flavor of coffee, coffee has no environmental factors, that is, there is no external yun state. If the system creates a separate object for each cup of coffee, then a lot of small objects need to be created. It's better to divide the coffee by the kind (i.e. "flavor"), and each flavor of coffee creates only one object and shares it.

In the language of coffee vendors, all coffee can be divided into "flavor" such as Capucino, Espresso, and so on, each flavor of coffee regardless of the number of cups sold, are all the same, indistinguishable. Sharing is the sharing of coffee flavors, the sharing of manufacturing methods, and so on. As a result, the enjoyment of meta-patterns for coffee stands means that there is no need for individual modulation of each part. The stall owner can make a one-of-a-kind coffee that is sold for a day at a time when needed.

Obviously, this is a good place to use the simple-to-enjoy meta mode. The system is designed as follows:

Using system;using System.collections;public abstract class order{//Sell coffee to guest public abstract void Serve (); Return the name of the coffee public abstract string Getflavor ();}  public class flavor:order{private string Flavor;  constructor, the intrinsic state is passed into public Flavor (string Flavor) {this.flavor = Flavor;  }//Return the name of the coffee public override string Getflavor () {return this.flavor;  }//Sell coffee to guest public override void Serve () {Console.WriteLine ("Serving flavor" + flavor);  }}public class flavorfactory{Private Hashtable flavors = new Hashtable (); Public Order GetOrder (string key) {if (! flavors. ContainsKey (key)) flavors.        ADD (Key, New Flavor (key));  Return (Order) Flavors[key]); } public int Gettotalflavorsmade () {return flavors.  Count;  }}public class client{private static Flavorfactory flavorfactory;  private static int ordersmade = 0;    public static void Main (string[] args) {flavorfactory = new flavorfactory ();    Takeorder ("Black Coffee"); Takeorder ("Capucino");    Takeorder ("Espresso");    Takeorder ("Capucino");    Takeorder ("Espresso");    Takeorder ("Black Coffee");    Takeorder ("Espresso");    Takeorder ("Espresso");    Takeorder ("Black Coffee");    Takeorder ("Capucino");    Takeorder ("Capucino");    Takeorder ("Black Coffee");    Console.WriteLine ("\ntotal Orders made:" + Ordersmade);  Console.WriteLine ("\ntotal Flavor objects made:" + Flavorfactory.gettotalflavorsmade ());    } private static void Takeorder (String aflavor) {Order o = Flavorfactory.getorder (Aflavor);    Sell Coffee to guest o.serve ();  ordersmade++; }}

Example 2: Example of a coffee shop

In front of the coffee stall project, all the coffee is not affected by the environment because there is no table for guests to sit on. In other words, coffee is only in its intrinsic state, that is, the type of coffee, not the state of the outside. consider a slightly larger café (Coffee shop) project. There are a lot of tables for guests to sit in, and the system needs to keep track of which table the coffee is sent to, in addition to the "flavor" of the coffee, so the coffee has a table for the outside state.

Because of the existence of the external Yun State, the simple-to-enjoy meta-mode no longer meets the requirements. The design of the system can take advantage of the simple-to-enjoy meta-mode with external Yun state. The code for the system is as follows:

Using system;using System.collections;public abstract class order{//Sell coffee to guest public abstract void Serve (table table); Return the name of the coffee public abstract string Getflavor ();}  public class flavor:order{private string Flavor;  constructor, the intrinsic state is passed into public Flavor (string Flavor) {this.flavor = Flavor;  }//Return the name of the coffee public override string Getflavor () {return this.flavor; }//Sell coffee to guest public override void Serve (table table) {Console.WriteLine ("Serving table {0} with flavor {1}", table.  number, flavor);  }}public class flavorfactory{Private Hashtable flavors = new Hashtable (); Public Order GetOrder (string key) {if (! flavors. ContainsKey (key)) flavors.        ADD (Key, New Flavor (key));  Return (Order) Flavors[key]); } public int Gettotalflavorsmade () {return flavors.  Count;  }}public class table{private int number;  public Table (int number) {this.number = number;  } public int Number {get {return number;} }}public class client{private static FLavorfactory flavorfactory;  private static int ordersmade = 0;    public static void Main (string[] args) {flavorfactory = new flavorfactory ();    Takeorder ("Black Coffee");    Takeorder ("Capucino");    Takeorder ("Espresso");    Takeorder ("Capucino");    Takeorder ("Espresso");    Takeorder ("Black Coffee");    Takeorder ("Espresso");    Takeorder ("Espresso");    Takeorder ("Black Coffee");    Takeorder ("Capucino");    Takeorder ("Capucino");    Takeorder ("Black Coffee");    Console.WriteLine ("\ntotal Orders made:" + Ordersmade);  Console.WriteLine ("\ntotal Flavor objects made:" + Flavorfactory.gettotalflavorsmade ());        } private static void Takeorder (String aflavor) {Order o = Flavorfactory.getorder (Aflavor);  Sell Coffee to Guest o.serve (++ordersmade); }}

Flyweight enjoy meta-mode usage Summary:

(1). The advantage of the flyweight mode is that it drastically reduces the number of objects in memory. However, the cost of doing this is also high:

(2). The Flyweight 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.

(3). The Flyweight - in-the-element mode takes the state of a meta object out of the way, while reading the external state makes the run time slightly longer.




Flyweight mode details-design mode (9)

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.