Enjoy the metadata mode: Flyweight from aliang. NET)

Source: Internet
Author: User
Flyweight is the most lightweight in boxing, that is, "Fly magnitude", which is translated by some authors as "Yu magnitude ". Here, the "share mode" is used to better reflect the intention of the mode.

The metadata mode supports a large number of fine-grained objects efficiently in a shared manner. The key to enabling shared object sharing is to differentiate the Internal State and External State ). The internal state is stored inside the object and does not change with the environment. Therefore, the status can be shared.

The external state changes with the environment and cannot be shared. The external status of the object must be saved by the client. After the object is created, the object must be uploaded to the object. The external status and internal status are independent of each other.

Application of the metadata-sharing model

The enjoy mode is widely used in the editor system. A text editor often provides many types of fonts, and the common practice is to make every letter a metadata object. The internal state of the object is this letter, while other information such as the position and style of letters in the text is the external state. For example, Letter a may appear in many places of the text. Although the location of these letters a is different from the model style, all these places use the same letter object. In this way, letter objects can be shared throughout the system.

Ii. Structure of the simple metadata-sharing model

In the simple metadata mode, all metadata objects can be shared. The simple metadata mode involves the following roles:

Abstract Flyweight role: this role is a superclass of all the specific Metadata classes and defines the public interfaces to be implemented for these classes. Operations that require External State can be passed in as parameters by calling commercial methods.

ConcreteFlyweight role: implements the interface defined by the abstract metadata role. If there is an inner state, it must provide storage space for the inner state. The inherent state of the object must be unrelated to the environment of the object, so that the object can be shared within the system.

FlyweightFactory role: this role is responsible for creating and managing the metadata. This role must ensure that the object can be shared by the system. When a client object calls a metadata object, the metadata factory role checks whether there is a composite requirement for the metadata object in the system. If you already have a metadata factory role, you should provide the existing metadata object. If the system does not have an appropriate metadata object, the metadata factory role should create a suitable metadata object.

Client role: This role must maintain a reference to all metadata objects. This role needs to store the external status of all the meta objects on its own.

Iii. Schematic source code of the simple metadata Mode

// Flyweight pattern -- Structural example  using System;using System.Collections;// "FlyweightFactory"class FlyweightFactory{  // Fields  private Hashtable flyweights = new Hashtable();  // Constructors  public FlyweightFactory()  {    flyweights.Add("X", new ConcreteFlyweight());    flyweights.Add("Y", new ConcreteFlyweight());    flyweights.Add("Z", new ConcreteFlyweight());  }  // Methods  public Flyweight GetFlyweight(string key)  {    return((Flyweight)flyweights[ key ]);  }}// "Flyweight"abstract class Flyweight{  // Methods  abstract public void Operation( int extrinsicstate );}// "ConcreteFlyweight"class ConcreteFlyweight : Flyweight{  private string intrinsicstate = "A";  // Methods  override public void Operation( int extrinsicstate )  {    Console.WriteLine("ConcreteFlyweight: intrinsicstate {0}, extrinsicstate {1}",       intrinsicstate, extrinsicstate );  }}/**//// <summary>/// Client test/// </summary>public class Client{  public static void Main( string[] args )  {    // Arbitrary extrisic state    int extrinsicstate = 22;         FlyweightFactory f = new FlyweightFactory();    // Work with different flyweight instances    Flyweight fx = f.GetFlyweight("X");    fx.Operation( --extrinsicstate );    Flyweight fy = f.GetFlyweight("Y");    fy.Operation( --extrinsicstate );    Flyweight fz = f.GetFlyweight("Z");    fz.Operation( --extrinsicstate );  }}

Iv. Structure of the composite metadata Mode

In the simple metadata mode, all the metadata objects can be directly shared. Next we will consider a complicated situation where some simple elements are combined using the compositing mode to form a composite object. Such compound object objects cannot be shared, but they can be divided into simple object objects, while the latter can be shared.

Shows the class diagram of the composite metadata mode:


The meta-mode involves abstract meta-roles, specific meta-roles, compound meta-roles, employee factory roles, and client roles.

Abstract meta-Role: this role is a superclass of all the specific meta-classes and defines the public interfaces to be implemented for these classes. Operations that require the External State can be passed in through the parameters of the method. Abstract metadata-sharing interfaces make it possible to enjoy the metadata, but do not force sub-classes to share. Therefore, not all metadata-sharing objects can be shared.

ConcreteFlyweight role: implements the interface defined by the abstract metadata role. If there is an inner state, it must provide storage space for the inner state. The inherent state of the object must be unrelated to the environment of the object, so that the object can be shared in the system. Sometimes a specific meta-role is called simply a specific meta-role, because a composite meta-role is composed of a specific meta-role.

UnsharableFlyweight role: the Objects represented by the composite meta-object cannot be shared. However, a composite meta-object can be decomposed into multiple combinations of simple meta-objects. A composite meta-role is also called a non-shareable meta-object.

FlyweightFactoiy: this role is responsible for creating and managing the metadata. This role must ensure that the object can be shared by the system. When a client object requests a metadata object, the metadata factory role needs to check whether there is a qualified metadata object in the system. If yes, the meta-factory role should provide the existing meta-object. If the system does not have an appropriate meta-object, the meta-factory role should create a new appropriate meta-object.

Client role: this role also needs to store the external status of all the metadata objects on its own.

Note: Because the composite metadata mode is complex, no schematic code is provided here. By combining the sharing mode with the merging mode, you can ensure that each simple element in the compound element has the same external state, and the inherent state of these simple elements is often different. For more information, see Chapter 31st of Java and mode.

5. Example of a coffee stall

In the Coffee Stall system, there is a series of Coffee "Flavor (Flavor )". The guests purchase coffee at the booth. All coffee is put on the desk, and the guests leave the booth after they get the coffee themselves. Coffee has an inherent state, that is, the flavor of coffee. Coffee has no environmental factors, that is, there is no external presence. If the system creates an independent object for each cup of coffee, many small objects need to be created. In this way, it is better to divide the coffee by type (I .e. "flavor"), and create only one object for each flavor of coffee and share it.

In terms of coffee vendors, all coffee can be classified into Capucino and Espresso by "flavor". No matter how many coffee cups are sold, they are all the same and cannot be distinguished. Sharing means sharing of coffee flavor and sharing of manufacturing methods. Therefore, for coffee stalls, The enjoy mode does not need to be separately modulated for each copy. The stall owner can work out a certain flavor of coffee that can be sold one day at a time as needed.

Obviously, the simple metadata mode is suitable here. The system is designed as follows:

UsingSystem;UsingSystem. Collections;Public Abstract ClassOrder {// Sell coffee to the guests  Public Abstract VoidServe ();// Return the coffee name  Public Abstract StringGetFlavor ();}Public ClassFlavor: Order {Private StringFlavor;// Constructor. The inner state is passed in as a parameter.  PublicFlavor (StringFlavor ){This. Flavor = flavor ;}// Return the coffee name  Public Override StringGetFlavor (){Return This. Flavor ;}// Sell coffee to the guests  Public Override VoidServe () {Console. WriteLine ("Serving flavor"+ Flavor );}}Public ClassFlavorFactory {PrivateHashtable flavors =NewHashtable ();PublicOrder GetOrder (StringKey ){If(! Flavors. ContainsKey (key) flavors. Add (key,NewFlavor (key ));Return(Order) flavors [key]);}Public IntGetTotalFlavorsMade (){ReturnFlavors. Count ;}}Public ClassClient {Private StaticFlavorFactory flavorFactory;Private Static IntOrdersMade = 0;Public Static VoidMain (String[] Args) {flavorFactory =NewFlavorFactory (); 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 VoidTakeOrder (StringAFlavor) {Order o = flavorFactory. GetOrder (aFlavor );// Sell coffee to the guestsO. Serve (); ordersMade ++ ;}}

6. Example of coffee house

In the previous coffee stall project, because there is no table for guests, all coffee has no environmental impact. In other words, there is only an inherent state of coffee, that is, the type of coffee, but there is no external state.

The following is a slightly larger Coffee Shop project. There are many tables in the room for guests to sit in. In addition to providing the "flavor" of the coffee, the system also needs to track which table the coffee was delivered to. Therefore, coffee has a table.

Because of the existence of the external memory status, the pure metadata mode without the external memory status does not meet the requirements. The system design can take advantage of the simple metadata-sharing mode with an exclusive state. The system code is as follows:

UsingSystem;UsingSystem. Collections;Public Abstract ClassOrder {// Sell coffee to the guests  Public Abstract VoidServe (Table table );// Return the coffee name  Public Abstract StringGetFlavor ();}Public ClassFlavor: Order {Private StringFlavor;// Constructor. The inner state is passed in as a parameter.  PublicFlavor (StringFlavor ){This. Flavor = flavor ;}// Return the coffee name  Public Override StringGetFlavor (){Return This. Flavor ;}// Sell coffee to the guests  Public Override VoidServe (Table table) {Console. WriteLine ("Serving table {0} with flavor {1 }", Table. Number, flavor );}}Public ClassFlavorFactory {PrivateHashtable flavors =NewHashtable ();PublicOrder GetOrder (StringKey ){If(! Flavors. ContainsKey (key) flavors. Add (key,NewFlavor (key ));Return(Order) flavors [key]);}Public IntGetTotalFlavorsMade (){ReturnFlavors. Count ;}}Public ClassTable {Private IntNumber;PublicTable (IntNumber ){This. Number = number ;}Public IntNumber {Get{ReturnNumber ;}}}Public ClassClient {Private StaticFlavorFactory flavorFactory;Private Static IntOrdersMade = 0;Public Static VoidMain (String[] Args) {flavorFactory =NewFlavorFactory (); 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 VoidTakeOrder (StringAFlavor) {Order o = flavorFactory. GetOrder (aFlavor );// Sell coffee to the guestsO. Serve (NewTable (++ ordersMade ));}}

7. When should I use the metadata sharing mode?

When all of the following conditions are met, you can consider using the enjoy mode:

A system has a large number of objects.
These objects consume a lot of memory.
Most of the statuses of these objects can be externalized.
These objects can be divided into many groups according to the inherent state. When the external object is removed from the object, each group can be replaced by only one object.
The software system does not depend on the identities of these objects. In other words, these objects can be undistinguished.
The system that meets the preceding conditions can use a shared object.

Finally, you need to maintain a table that records all the existing metadata in the system in the metadata-sharing mode, which consumes resources. Therefore, the metadata mode should be used only when there are enough metadata instances available for sharing.

8. Advantages and disadvantages of the shared Element Model

The advantage of the Meta mode is that it greatly reduces the number of objects in the memory. However, it also pays a very high price to achieve this:

The metadata mode makes the system more complex. In order for objects to be shared, some States need to be externalized, which complicate the logic of the program.
The metadata mode externalizes the state of the object, and reads the external State to slightly extend the running time.

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.