Enjoy meta mode

Source: Internet
Author: User

1. What is the mode of sharing?

Flyweight pattern: Efficiently supports a large number of fine-grained objects in a shared manner. Reduces the performance consumption of system-created object instances by reusing objects that already exist in memory.

The English of flyweight is a professional language from sports, especially the lightest level in boxing, wrestling and weightlifting competitions. Porting this word to software engineering is also used to represent a particularly small object, a fine-grained object. As for why the translation of flyweight to "enjoy meta", it can be understood as a shared meta-object, that is, the sharing of fine-grained objects.

In object-oriented, the loss of resources and performance resulting from the creation, destruction, and storage of a large number of fine-grained objects may create bottlenecks during system operation. So how do you avoid producing a large number of fine-grained objects without affecting the way the system operates using object-oriented methods? The enjoy meta-mode provides a better solution.


2, enjoy the meta-mode class diagram:



Enjoy the meta-mode is divided into intrinsic state and the state of the outside, followed by the use of case analysis.


3. Case

Case requirements: In Gobang, there will be a lot of sunspots and white, but for every sunspot or white child to create an object, it will consume memory too much. Can we share object instances? So that there are only "sunspots" and "white" two objects throughout the game. This requires the use of the enjoy meta mode.

First create a chess piece abstract class as a piece of the superclass, containing a piece of the identity of the property:

<span style= "FONT-SIZE:18PX;"  >/** * Requirements: A piece of super class, containing a pawn category of attributes, logo specific type of pawn * @author Dragon over the river * */public abstract class Abstractchessman {//Pawn category protected String chess;//Construction method Public Abstractchessman (String chess) {this.chess = chess;} Show pawn Information public void Show () {System.out.println (this.chess);}} </span>


Sunspot class:

<span style= "FONT-SIZE:18PX;" >/** * Demand: Sunspot class * @author Dragon over the river * */public class Blackchessman extends Abstractchessman {/* * constructor, initialize black pawn */public blackch Essman () {super (""); System.out.println ("--a black piece was born! --");}} </span>


White sub-Category:

<span style= "FONT-SIZE:18PX;" >/** * Demand: White pawn * @author dragon over the river * */public class Whitechessman extends Abstractchessman {/* * Construction method, initialize black pawn */public Whitech Essman () {super ("0"); System.out.println ("--a white piece was born! --");}} </span>


Below to design pieces factory class, Pawn factory class We are designed as a singleton model, the class is used to produce pieces object instances, and put into the cache, the next time you get a pawn object from the cache. The contents are as follows:

<span style= "FONT-SIZE:18PX;" >import java.util.hashmap;import java.util.hashtable;import java.util.map;/** * Requirements: Pawn factory for the production of pawn object instances, and put into the cache, Complete in single-case mode * @author Dragon Crossing * */public class Chessmanfactory {//Singleton mode private static chessmanfactory chessmanfactory = new Chess Manfactory ();//Cache Shared Object Private final Hashtable<character, abstractchessman> cache = new Hashtable<character, Abstractchessman> ();//construction Method Privatization private chessmanfactory () {}//obtains a singleton factory object public static Chessmanfactory getinstance () { return chessmanfactory;} /* * Get chess pieces */public Abstractchessman getchessmanobject (char c) {//Get a Pawn object instance from the cache Abstractchessman Abstractchessman = This.cache.get (c);//null if (Abstractchessman==null) {//Description There is no instance of the pawn object in the cache, you need to create switch (c) {case ' B ': Abstractchessman = new Blackchessman (); Break;case ' W ': Abstractchessman = new Whitechessman (); Break;default:system.out.println ("illegal character, please reenter! "); break;} If there is an illegal character, then the object must still be empty, so then make a judgment if (abstractchessman!=null) {//Put in the cache This.cache.put (c, Abstractchessman);}} Returns the return AB if a pawn object exists in the cacheStractchessman;}} </span>


Test through the client:

<span style= "FONT-SIZE:18PX;"  >import java.util.random;/** * Requirements: Client (test Class) * @author dragon across the river * */public class Test {public static void main (string[] args) {//create factory Chessmanfactory chessmanfactory = Chessmanfactory.getinstance ();//random number, used to generate a pawn object random random = new random (); int Radom = 0;  Abstractchessman Abstractchessman = null;//randomly obtains pawn for (int i = 0; i <; i++) {radom = Random.nextint (2); switch (Radom) {Case 0://get black Pawn Abstractchessman = chessmanfactory.getchessmanobject (' B '); break;case 1://get black Pawn Abstractchessman = Chessmanfactory.getchessmanobject (' W '); if (abstractchessman!=null) {abstractchessman.show ();}}}} </span>


After execution, we found that "a black piece was born!" "and" a white piece was born! "Each executed once, explained that in many pieces only one black piece and a white pawn, realizes the object the sharing, this is the enjoyment yuan.


4, the need to change

We also need to change the requirements because the pieces must have a position, so we also need to make the pieces show position. Obviously, the pieces of objects can be shared, but the pieces of the position are not the same, is not able to share, this long involved in the two states to enjoy the meta-mode: The intrinsic status (Internal state) and the State of the outer Yun (External).

Intrinsic state:

The intrinsic state of the shared meta object is not changed with the change of environment, it is the state information stored inside the object of the privilege, so the intrinsic state is shareable, and its value is exactly the same for any of the object of the privilege. Think of the above "sunspots" and "white Son", it represents the state is intrinsic state.

The state of the outer Yun:

The second state of the shared meta-object is the outer state, which changes as the environment changes, so it is not shareable, and its value may be different for different objects of enjoyment. The outer state of the object must be saved by the client, and once the object is created, it needs to be passed into the inside of the object, like the location information of Gobang, which represents the external state of the object.

Therefore, the external state and intrinsic state of the shared meta object are two separate states, which are not related to each other.


5. Realize the state of external Yun

The exogenous state variables need to change with the change of environment, we need to increase the position of the pieces in the abstract chess class, i.e. coordinate information, and the method content of setting the position.

The abstract classes that increase the position information of a pawn are:

<span style= "FONT-SIZE:18PX;"  >/** * Requirements: A piece of super class, containing a pawn category of attributes, logo specific type of pawn * @author Dragon over the river * */public abstract class Abstractchessman {//Pawn category protected String chess;//pawn coordinate protected int x;protected int y;//construction method public Abstractchessman (String chess) {this.chess = chess;} The coordinates are set public to abstract void point (int x,int y);//Display pawn Information public void Show () {System.out.println (this.chess+ "(" +this.x+ "," +this.y+ ")");}} </span>


Perfect after the Sunspot class:

<span style= "FONT-SIZE:18PX;" >/** * Demand: Sunspot class * @author Dragon over the river * */public class Blackchessman extends Abstractchessman {/* * constructor, initialize black pawn */public blackch Essman () {super (""); System.out.println ("--a black piece was born! --");} /* * Override method */@Overridepublic void point (int x, int y) {this.x = X;this.y = Y;this.show ();}} </span>


The perfect white sub-category is:

<span style= "FONT-SIZE:18PX;" >/** * Demand: White pawn * @author dragon over the river * */public class Whitechessman extends Abstractchessman {/* * Construction method, initialize black pawn */public Whitech Essman () {super ("0"); System.out.println ("--a white piece was born! --");} /* * Override method */@Overridepublic void point (int x, int y) {this.x = X;this.y = Y;this.show ();}} </span>


There is no need to make any changes in the pawn factory because we get the shared object in the pawn Factory, and the external State (location information) needs to be set on the client.

Client:

<span style= "FONT-SIZE:18PX;"  >import java.util.random;/** * Requirements: Client (test Class) * @author dragon across the river * */public class Test {public static void main (string[] args) {//create factory Chessmanfactory chessmanfactory = Chessmanfactory.getinstance ();//random number, used to generate a pawn object random random = new random (); int Radom = 0;  Abstractchessman Abstractchessman = null;//randomly obtains pawn for (int i = 0; i <; i++) {radom = Random.nextint (2); switch (Radom) {Case 0://get black Pawn Abstractchessman = chessmanfactory.getchessmanobject (' B '); break;case 1://get black Pawn Abstractchessman = Chessmanfactory.getchessmanobject (' W '); if (abstractchessman!=null) {abstractchessman.point (I, Random.nextint (15));}}}} </span>

  

After testing, we are able to get gobang positions with different positions. We get, the focus of the meta-mode is to share meta-objects, reduce the use of memory space, improve system performance. The external state of the shared meta-object is stored through the client to save the incoming, it is possible to change, so in our software system design, we must share the intrinsic state of the meta-object and the external state, can not be confused, more can not be related to each other, the two should be separated from each other.


6, enjoy the characteristics of the meta-object:
the focus of the enjoy meta-mode is "share object instances, reduce memory space". If you do not need an object instance, you need to go to the new object, and if you can take advantage of other object instances, you should share the object instance. Share fine-grained objects, reduce memory space and improve system performance;

"The package changes the part", here the intrinsic state is the invariant part, the outer state is the change of the part, so we make the intrinsic state in the class is passed in, and the state is from the client incoming;


7, the use of the scene:


When there are more instances of an object type in the system;

When the system design time, the object instance really has the difference classification very few, for example for the pinyin, if each letter is new an object instance, we need 52 objects, so the instance is too many, the enjoyment meta-mode is generally gives the local memory resource saving scheme, is not suitable for the Internet Distributed application situation;

The singleton mode itself is a kind of enjoy meta mode, with only one object instance in the singleton mode, shared by other objects.


8. Enjoy meta-mode in Java

In Java, the integer class under the Lang Packet, for an integer object that is frequently used in the range of 128 to 127, is created when the class is loaded and saved in the cache array, once the program calls the ValueOf method, if the value of I is 128 to 127 In the cache cache array to take the integer object instead of creating a new object, this is the application of the enjoy meta-mode.




Enjoy meta mode

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.