Java design mode of the sharing meta-mode

Source: Internet
Author: User
Tags getcolor gety

At present, our country is vigorously advocating the construction of a harmonious society, one of the most important component is to build a resource-saving society, "waste shameful, thrifty glorious." In the software system, sometimes there will be a waste of resources, for example, in computer memory to store multiple identical or very similar objects, if the number of these objects will cause the system to run too high cost, memory belongs to the computer's "scarce resources", should not be used to "waste", So is there a technology that can be used to save memory space and to share access to these same or similar objects? The answer is yes, this technology is what we will learn in this chapter to enjoy the meta-model.

14.1 The design of chess chess Pieces

Sunny software company wants to develop a go software, its interface effect 14-1 shows:

Figure 14-1 Weiqi Software interface

Sunny software company developers through the Go Software analysis, found in the chess board contains a large number of sunspots and white children, their shape, size are identical, just appear in different locations. If each piece is stored as a separate object in memory, it will cause the go software to run with a large amount of memory space, how to reduce the operating cost, improve the system performance is sunny company developers need to solve a problem . In order to solve this problem, sunny Company's developers decided to use the module to design the Chess object of the Go software, then how to save memory and improve the system performance of the meta-mode? Don't worry, let us formally enter the learning of the meta-mode.

14.2 Enjoy meta mode overview

When a software system produces too many objects at run time, it will cause problems such as high running costs and degraded system performance. For example, there are many duplicate characters in a text string, if each character is represented by a separate object, it will take up more memory space, how can we avoid a large number of identical or similar objects in the system, without affecting the client program to manipulate these objects in an object-oriented way? The sharing model is being created to solve this kind of problem. The enjoy meta-mode implements the reuse of identical or similar objects by sharing technology, and logically each occurrence of the characters has an object corresponding to it, but physically they share the same object, which can appear in different places of a string, and the same character object points to the same instance. In the enjoy meta mode, the place where these shared instance objects are stored is called the Flyweight pool. We can create a single object for each of the different characters, place it in the pool of enjoyment, and then remove it from the pool of privileges when needed. 14-2 is shown below:

Figure 14-2 character Fu Yuan object

The enjoy meta-mode efficiently supports the reuse of a large number of fine-grained objects in a shared way, and the key to sharing the meta-object is to differentiate between internal states (intrinsic State) and external states (extrinsic state). The following is a brief introduction to the internal and external states of the sharing element:

(1) The internal state is a state stored inside the object that is not changed with the environment and the internal state can be shared . such as the content of the character, does not change with the external environment changes, regardless of the environment under the character "a" is always "a", will not become "B".

(2) The external state is a state which changes with the environment and cannot be shared . The external state of the enjoy meta object is typically saved by the client, and is then passed into the object's interior once it is created. An external state is independent from the other external state. such as the color of the character, you can have different colors in different places, for example, some "a" is red, some "a" is green, the size of the character is also the same, some "a" is fifth, some "a" is the number fourth word. and the color and size of the characters is two independent external states, they can change independently, with no effect on each other, the client can be used to inject the external state into the element object.

Because of the distinction between the internal state and the external state, we can store objects with the same internal state in the pool, and the objects in the pool can be shared, and when needed, the objects are removed from the pool of privileges to implement the reuse of objects. By injecting different external states into the object being fetched, you can get a series of similar objects that actually store only one copy in memory.

The enjoy meta mode is defined as follows:

Flyweight Pattern: Use sharing technology to effectively support the reuse of a large number of fine-grained objects. The system uses only a small number of objects, and these objects are very similar, the state changes very small, you can achieve multiple reuse of objects. Because the enjoy meta mode requires that the object that can be shared must be a fine-grained object, it is also known as lightweight mode, which is an object-structured pattern.

The structure of the enjoy meta-mode is more complex, and is commonly used in conjunction with Factory mode, and in its structure diagram contains a class of the enjoy meta factory, which is shown in Figure 14-3:

Figure 14-3 Enjoy meta-mode structure diagram

The following roles are included in the enjoy meta-mode structure diagram:

Flyweight (abstract Class): typically an interface or abstract class that declares a common method of sharing meta-classes in an abstract class, which can provide external data (internal state) to the outside world, and can also be used to set the outer data (external State).

Concreteflyweight (specific to the class): it implements an abstraction of the class, which is an instance of the enjoyment meta-object, and provides storage space for the internal state in the specific class. Typically, we can design a specific class of benefits in conjunction with a singleton pattern, providing a unique element of enjoyment for each of the specific class of classes.

Unsharedconcreteflyweight (non-shared-specific): Not all subclasses of the abstract-sharing class need to be shared, and subclasses that cannot be shared can be designed to be unshared, and can be created directly by instantiation when an object of a non-shared-specific class is needed.

Flyweightfactory (enjoy Meta factory Class): The enjoy meta-factory class is used to create and manage the privilege meta-object, which is programmed for the abstraction of the class, and stores various types of specific objects in a single pool, and the pool is generally designed as a collection of "key-value pairs" (which can also be a collection of other types). Can be designed in conjunction with the factory model; When a user requests a specific object, the add-in factory provides an instance that is stored in the pool that was created or creates a new instance (if it does not exist), returns the newly created instance, and stores it in the pool of privileges.

The enjoy Meta factory class is introduced in the enjoy meta-mode, and the function of the enjoy meta-factory class is to provide a pool of privileges for storing the object of the object, when the user needs the objects, first from the enjoyment pool, if the pool does not exist, create a new object to return to the user, and save the new objects in the pool. The code for the typical enjoy Meta factory class is as follows:

Class Flyweightfactory {

Defines a hashmap for storing the privilege meta-object, implementing the pool of privileges

Private HashMap flyweights = Newhashmap ();

Public Flyweight getflyweight (String key) {

If the object exists, it is fetched directly from the pool of privileges

if (Flyweights.containskey (key)) {

Return (Flyweight) flyweights.get (key);

}

If the object does not exist, first create a new object to add to the pool, and then return

else {

Flyweight FW = Newconcreteflyweight ();

Flyweights.put (KEY,FW);

return FW;

}

}

}

The design of the enjoy meta-class is one of the main points of the enjoy meta-mode, in which the internal state and the external state are handled separately, and the internal state is usually used as the member variable of the class, and the external state is added to the class of the privilege by injection. The typical class of privilege code is as follows:

Class Flyweight {

// internal state intrinsicstate is a member variable, and its internal state is consistent with the same object

Private String intrinsicstate;

Public Flyweight (String intrinsicstate) {

This.intrinsicstate=intrinsicstate;

}

External state extrinsicstate are externally set when used, and are not guaranteed to exist in the shared meta object, even if the same object can pass in different external states at each invocation

public void operation (String extrinsicstate) {

......

}

}

14.3 Complete Solutions

In order to save storage space and improve the performance of the system, sunny company developers use the enjoy meta-mode to design chess pieces in the Go software, the basic structure of 14-4 shows:


Figure 14-4 Go chess piece structure diagram

In Figure 14-4, Igochessman acts as an abstract-class, and Blackigochessman and Whiteigochessman act as the specific class of the privilege, and Igochessmanfactory act as the class of the enjoy meta factory. The complete code looks like this:

ImportJava.util.*; //Go Chess class: Abstract enjoy meta classAbstract classIgochessman { Public AbstractString GetColor ();  Public voiddisplay () {System.out.println ("Pawn Color:" + This. GetColor ()); }  }    //Black Chess class: specific to enjoy the meta-classclassBlackigochessmanextendsIgochessman { PublicString GetColor () {returnBlack; }     }    //White Chess class: specific to enjoy the meta-classclassWhiteigochessmanextendsIgochessman { PublicString GetColor () {returnWhite; }  }    //Go Chess Factory Category: Enjoy the meta-factory class, using a single-case model for designclassIgochessmanfactory {Private StaticIgochessmanfactory instance =Newigochessmanfactory (); Private StaticHashtable HT;//use Hashtable to store the access meta object as a pool of privileges          Privateigochessmanfactory () {HT=NewHashtable ();          Igochessman Black,white; Black=NewBlackigochessman (); Ht.put ("B", Black); White=NewWhiteigochessman (); Ht.put ("W", white); }            //returns the unique instance of the enjoy Meta factory class     Public Staticigochessmanfactory getinstance () {returninstance; }            //use key to get the Hashtable object stored in the     Public Staticigochessman Getigochessman (String color) {return(Igochessman) ht.get (color); }  }  

Write the following client test code:

classClient { Public Static voidMain (String args[]) {Igochessman black1,black2,black3,white1,white2;                    Igochessmanfactory Factory; //get the Enjoy Meta factory objectFactory =igochessmanfactory.getinstance (); //three sunspots obtained through the Mövenpick plantBlack1 = Factory.getigochessman ("b"); Black2= Factory.getigochessman ("b"); Black3= Factory.getigochessman ("b"); System.out.println ("Determine if the two sunspots are the same:" + (black1==Black2)); //get two white children through the Mövenpick factoryWhite1 = Factory.getigochessman ("W"); White2= Factory.getigochessman ("W"); System.out.println ("Judge whether the two white children are the same:" + (white1==white2)); //Show PiecesBlack1.display ();          Black2.display ();          Black3.display ();          White1.display ();      White2.display (); }  }  

Compile and run the program with the following output:

Determine if two sunspots are the same: true

Determine if two white children are the same: true

Pawn Color: Black

Pawn Color: Black

Pawn Color: Black

Chess piece Color: White

Chess piece Color: White

As can be seen from the output, although we have three sunspot objects and two white sub-objects, they have the same memory address, which means they are actually the same object. When implementing the enjoy Meta factory class, we used the singleton mode and the simple Factory mode to ensure the uniqueness of the element factory object and to provide a factory method to return the object to the client.

14.5 Solutions with external states

Sunny software company developers through the further analysis of chess pieces, found that although the black pieces and white pieces can be shared, but they will be displayed in different places of the board, how to let the same sunspots or white children can be repeated multiple times and located in a different place of the chessboard? The solution is to define the position of the pawn as an external state of the pawn and set it when needed. Therefore, we have added a new class coordinates (coordinate Class) in Figure 14-4 to store the position of each piece, as shown in Figure 14-5 after the modified structure:

Figure 14-5 The Go chess piece structure after the introduction of the external state

In Figure 14-5, in addition to adding a coordinate class coordinates, the display () method in the abstract-enjoy meta-class Igochessman also adds a coordinates-type parameter that specifies its coordinates when the pawn is displayed. The code for the coordinates class and the modified Igochessman class is as follows:

classcoordinates {Private intx; Private inty;  PublicCoordinates (intXinty) { This. x =x;  This. y =y; }             Public intGetX () {return  This. x; }             Public voidSetX (intx) { This. x =x; }             Public intGetY () {return  This. Y; }             Public voidSety (inty) { This. y =y; }  }     //Go Chess class: Abstract enjoy meta classAbstract classIgochessman { Public AbstractString GetColor ();  Public voidDisplay (coordinates coord) {System.out.println ("Pawn Color:" + This. GetColor () + ", Pawn Position:" + coord.getx () + "," +coord.gety ()); }  }  

The client test code is modified as follows:

classClient { Public Static voidMain (String args[]) {Igochessman black1,black2,black3,white1,white2;                    Igochessmanfactory Factory; //get the Enjoy Meta factory objectFactory =igochessmanfactory.getinstance (); //three sunspots obtained through the Mövenpick plantBlack1 = Factory.getigochessman ("b"); Black2= Factory.getigochessman ("b"); Black3= Factory.getigochessman ("b"); System.out.println ("Determine if the two sunspots are the same:" + (black1==Black2)); //get two white children through the Mövenpick factoryWhite1 = Factory.getigochessman ("W"); White2= Factory.getigochessman ("W"); System.out.println ("Judge whether the two white children are the same:" + (white1==white2)); //show the pieces and set the coordinate position of the piecesBlack1.display (NewCoordinates ()); Black2.display (NewCoordinates (3,4)); Black3.display (NewCoordinates (1,3)); White1.display (NewCoordinates (2,5)); White2.display (NewCoordinates (2,4)); }  }  

Compile and run the program with the following output:

Determine if two sunspots are the same: true

Determine if two white children are the same: true

Chess piece color: black, pawn Position:

Pawn color: Black, pawn Position: 3,4

Pawn color: Black, pawn Position: 1,3

Pawn color: white, pawn Position: 2,5

Pawn color: white, pawn Position: 2,4

As you can see from the output, each time the display () method is called, different external states-coordinate values are set, so the same piece objects have the same color, but their coordinate values are different and will be displayed in different positions on the chessboard.

"Liu Wei Http://blog.csdn.net/lovelion"

Java design mode of the sharing meta-mode

Related Article

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.