Motivation:In our object-oriented design process, we often face the problem of too many object instances. If there are too many object instances, this will be a bottleneck for our system performance improvement. Suppose we want to design a star scene, and now we need to instance the star object, we can instance each star, but as we increase the number of star objects in our instance, the whole scenario is getting slower and slower, if you have more than 1000 stars for maintenance, This is a thankless job. We must find a proper solution to the above problems.
Definition: Meta mode (Flyweight), Using the sharing technology to effectively support a large number of fine-grained objects.
Structure:
Roles involved:
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 an internal status exists, you must provide storage space for the internal status..The internal status of the object must be unrelated to the environment of the object, so that the object can be shared within 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.
Internal and external statuses:A shared part within a shared object that does not change with the environment can be called the internal state of the object. If the environment changes, the non-shared state is called the external state.
A typical example of the enjoy meta mode is a file processor that represents characters in a graphical structure. One approach is that each font has its own font appearance, metrics, and other format information, but this consumes thousands of bytes for each character. Instead, each character refers to a shared font object, which is shared by other characters with common characteristics. Only each character (in a file or on a page) to store the data.
CodeExample:
Abstract metadata: flycharacter
Package COM. jin. model. flyweight; public class flycharacter {// intrinsic stateprotected char symbol; protected int size; protected string font; Public flycharacter (char symbol, int size, string font) {This. symbol = symbol; this. size = size; this. font = font;} public void display (position) {system. out. println ("Symbol:" + symbol + "Size:" + size + "position: X" + position. getpos_x () + "Y" + position. getpos_y ());}}
Specific shard: characloud
Package com. Jin. model. flyweight; public class characloud extends flycharacter {public characloud () {super ('A', 10, "");}}
Specific shard: characterb
Package com. Jin. model. flyweight; public class characterb extends flycharacter {public characterb () {super ('B', 11, "");}}
Specific shard: characterz
Package com. Jin. model. flyweight; public class characterz extends flycharacter {public characterz () {super ('Z', 12, "Arial ");}}
Share Factory: characterfactory
Package COM. jin. model. flyweight; import Java. util. hashmap; import Java. util. map; public class characterfactory {// keeps the character object by specifying key/value. private Static Map <character, flycharacter> charaters = new hashmap <character, flycharacter> (); public static flycharacter getcharacter (character key) {flycharacter character = NULL; If (charaters. containskey (key) {character = charaters. get (key);} else {try {character = (flycharacter) class. forname ("com. jin. model. flyweight. character "+ key. tostring (). touppercase ()). newinstance ();} catch (exception e) {e. printstacktrace ();} charaters. put (Key, character);} return character;} public static int getcount () {return charaters. size ();}}
External status: Position
Package COM. jin. model. flyweight; public class position {private int pos_x; private int pos_y; public position () {}public position (INT posx, int posy) {pos_x = posx; pos_y = posy ;} public int getpos_x () {return pos_x;} public void setpos_x (INT posx) {pos_x = posx;} public int getpos_y () {return pos_y;} public void setpos_y (INT posy) {pos_y = posy ;}}
Client: Client
Package COM. jin. model. flyweight; import Java. util. random; public class client {public static void main (string [] ARGs) {flycharacter character; string text = "abzabbzz"; char [] letters = text. tochararray (); random = new random (); For (INT I = 0; I <letters. length; I ++) {character = characterfactory. getcharacter (letters [I]); character. display (New Position (random. nextint (50), random. nextint (50);} system. out. println ("created in total" + characterfactory. getcount () + "character object ");}}
Running result:
Applicability:
The effectiveness of the flyweight mode depends largely on how it is used and where it is used.When the following conditions are metUse the flyweight mode.
- One applicationProgramA large number of objects are used.
- Because a large number of objects are used, the storage overhead is very high.
- Most States of an object can be changed to external states.
- If you delete the external state of an object, you can replace multiple groups of objects with a relatively small number of shared objects.
- Applications do not rely on object identifiers.
Disadvantages:
- 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.