Design Pattern 21-flyweight (Structural)

Source: Internet
Author: User
Tags getcolor gety
1. Explanation of the definition of the 1.1 yuan mode in the shared element mode (Structural)

The sharing technology is used to effectively support a large number of fine-grained objects.
Share: Share the internal status
Key points of the 1.2 yuan Sharing Model

The focus is on changing and changing the separation.
Divides the state of an object into internal and external States. The internal State remains unchanged and the external state changes.
The internal state is managed in the object through the internal method, and the external information can be deleted or saved through the external.
1.3 Structure Diagram and description

 
The meta-mode involves abstract meta-roles, specific (simple) Meta-roles, compound meta-roles, employee factory roles, and client roles.

Abstract flyweight ):This role is a superclass of all the specific Metadata classes. It specifies public interfaces or abstract classes 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.

The specific concreteflyweight role:Implement the interface specified 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:Objects represented by a composite meta-object cannot be shared. However, a composite meta-object can be divided into multiple combinations of meta-objects. A composite meta-role is also called a non-shareable meta-object. This role is rarely used.

Flyweightfactoiy:This role is responsible for creating and managing the role. 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 meta objects on its own.
1.4 sample code of the metadata Mode

Package demo19.flyweight. example2;/***** you can use this interface to enjoy the metadata that can be accepted and applied to the external State */public interface flyweight {/*** example operation, input the sample parameter ** @ Param extrinsicstate * for the external status, */Public void operation (string extrinsicstate );} **************************************** **************************************** * ***************** package demo19.flyweight. example2;/*** metadata object */public class concreteflyweight implements flyweight {/*** example, describing the internal status */private string intrinsicstate;/*** constructor, incoming data of the internal state of the object to be shared ** @ Param state * Data of the internal state of the object to be shared */Public concreteflyweight (string state) {This. intrinsicstate = State;} public void operation (string extrinsicstate) {// specific function processing, you may use the internal and external statuses of the object you want to share }}***************************** **************************************** * **************************** package demo19.flyweight. example2;/*** do not need to share the flyweight object. Generally, the shared metadata object is used as a subnode, the combined object */public class unsharedconcreteflyweight implements flyweight {/*** describes the object state */private string Allstate; Public void operation (string extrinsicstate) {// specific function processing }}******************************* **************************************** * ************************** package demo19.flyweight. example2; import Java. util. hashmap; import Java. util. map;/*** */public class flyweightfactory {/*** caches multiple flyweight objects. Here we just show you */private Map <string, flyweight> fsmap = new hashmap <string, flyweight> ();/*** obtain the key of the object corresponding to the key ** @ Param key * to obtain the key of the object, the basic steps in this method are as follows: // 1: first, find out from the cache whether the flyweight object of the key exists. flyweight F = fsmap. get (key); // 2: If yes, return the corresponding flyweight object if (F = NULL) {// 3: If no exist // 3.1: create a new flyweight object F = new concreteflyweight (key); // 3.2: add this new flyweight object to the cache fsmap. put (Key, f); // 3.3: Then return this new flyweight object} return F ;}} **************************************** **************************************** * ***************** package demo19.flyweight. example2;/*** client object, which usually maintains a reference to flyweight, calculate or store one or more flyweight external States */public class client {// specific function processing}
The essence of the 1.5 yuan Model

Separation and sharing
Advantages and disadvantages of 1.6 Yuan

Advantages:Reduces the number of objects and saves memory space
Disadvantages:Additional overhead is required to maintain shared objects.
1.7 when?

1.7.1 if a program uses a large number of fine-grained objects
1.7.2 if most States of an object can be changed to external States (for example, they can be calculated) or transmitted from the external, you can use the enjoy mode to separate the internal and external states.
2. Case study of using the shared Element Model

For example, if go has 300 chess pieces and uses the general design mode to create a class, it will be very troublesome if every chess piece uses an object, and define their respective positions on the board ..... and so on. If we use the henyuan mode to implement it, we will use two objects: one black and one white. In this way, as for the different positions of the pawns, it is only the different external manifestation of the object or the external state. In this way, more than three hundred objects are reduced to two objects. The metadata mode supports a large number of fine-grained objects in a shared manner. Specifically, it points all objects in the same State to the same reference, this solves the memory pressure caused by the system when creating a large number of objects.
The sample code is as follows:
2.1 yuan interface, through which the yuan can be accepted and act on external States

Package demo19.flyweight. example1;/*** abstract chess piece interface ** @ author Wang yuchao * @ date 2013-7-31 */public interface ichessflyweight {Public String getcolor (); public void show (point );}
2.2 yuan object
Package demo19.flyweight. example1;/*** implementation class of the specific chess piece object ** @ author Wang yuchao * @ date 2013-7-31 */public class concretechessflyweight implements ichessflyweight {private string color; Public String getcolor () {return color;} public concretechessflyweight (string color) {This. color = color;} public void show (point) {system. out. println ("This chess is" + color + ", point X:" + point. getx () + "Y:" + point. gety ());}}
2.3 objects that do not need to be shared, that is, external dynamic variables
Package demo19.flyweight. example1;/*** attributes of external dynamic changes of pawns ** @ author Wang yuchao * @ date 2013-7-31 */public class point {private int X; private int y; public point (int x, int y) {This. X = x; this. y = y;} public int getx () {return X;} public int Gety () {return y;} @ overridepublic string tostring () {return "point [x =" + x + ", y =" + Y + "]" ;}}
2.4 yuan model object Factory
Package demo19.flyweight. example1; import Java. util. hashmap; import Java. util. map;/*** the metadata model object factory ** @ author Wang yuchao * @ date 2013-7-31 */public class chessflyweightfactory {private Map <string, ichessflyweight> chessmap = new hashmap <string, ichessflyweight> (); Public ichessflyweight getchess (string key) {If (! Chessmap. containskey (key) {chessmap. Put (Key, new concretechessflyweight (key) ;}return chessmap. Get (key );}}
2.5 client call
Package demo19.flyweight. example1; public class client {public static void main (string [] ARGs) {chessflyweightfactory = new chessflyweightfactory (); point; string white = "white "; string black = ""; point = new point (0, 0); factory. getchess (white ). show (point); point = new point (10, 10); factory. getchess (white ). show (point); point = new point (100,100); factory. getchess (black ). show (point); point = new point (200,200); factory. getchess (black ). show (point );}}

After carefully matching the sample code, the code finds that there is no [flyweight object that does not need to be shared] Actually, it is the point class, but the point class does not inherit the flyweight interface. Objects that do not need to be shared are rarely used.

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.