JAVA design Pattern (23)-FlyWeight (__java) mode

Source: Internet
Author: User
Tags int size

definition: the use of shared technology to effectively support a large number of fine-grained objects.

Type: Object-structured pattern

class Diagram:



structure of the flyweight pattern

abstract Flyweight Role: describes an interface through which Flyweight can be accepted and acting on an external state. The concreteflyweight role: implements the flyweight interface and adds storage space for internal state (if any). The Concreteflyweight object must be shareable. The state it stores must be internal; that is, it must be independent of the scene of the Concreteflyweight object. Composite (unsharableflyweight) Role: The object represented by the composite element role cannot be shared, but a composite element object can be decomposed into multiple combinations that are itself a purely exclusive object. The composite element role is also called an unshared object. This role is generally rarely used. The flyweightfactoiy role: This role is responsible for creating and managing the privilege role. This role must ensure that the privilege object can be properly shared by the system. When a client object requests a privilege object, the Meta factory role needs to check if there is already a qualifying object in the system, and if so, the Meta factory role should provide this existing object of entitlement, and if there is not a proper object in the system, The Meta factory role should create a new appropriate object for the privilege. Client Role: maintains a reference to the flyweight, calculates or stores an external state of (multiple) flyweight.


All states of the privilege object are divided into two classes, the internal state and the external state .
Internal status (Internal State). It will not change with the environment, stored in the inside of the object, so the intrinsic state can be shared, and for any one object, its value is exactly the same. In our example, the symbol attribute of the character class, which represents the state is the intrinsic state. external status (External state). It changes with the environment, so it cannot be shared, and it may be a different value for a different object. The external state of the privilege object must be saved by the client, which is then passed into the inside of the object when it needs to be used when the object is created.

The state required for flyweight execution must be an internal or external state, the internal state is stored in the Concreteflyweight object, and the external object is stored or computed by the client object, which is passed to the user when it invokes the operation of the flyweight object.


An object-oriented text editor is now designed to illustrate the application of the meta pattern. Suppose we were to design a text editor, and it had to create character objects to represent each character in the document, now let's consider what information the character object holds. such as: font, font size and location, and so on information.
A document usually contains a number of character objects that require large capacity memory. It is worth noting that ordinary characters are made up of numbers, letters and other characters (they are fixed, knowable), these character objects can share information such as font and font size, now their proprietary properties are only left, each character object just keep them in the location of the document OK, By analyzing we have reduced the memory requirements of the editor.


First we define a character Fu Yuan class in which the symbol, font, and font size are internal, while the position is an external state.

Abstract class FlyWeight
Icharacter {	//Word Fu Yuan
	protected char symbol;
	protected int size;
	protected String font;

	public abstract void display ();
}


We then define the privilege class for the specific character a, and initialize the internal status symbol, font, and font size, and the other characters B to the Z-class are similar.

Concreteflyweight
class Charactera extends Icharacter {//specific character A public

	Charactera () {
		symbol = ' a ';
		size = ten;
		Font = "Song body";
	}

	@Override public
	void display () {
		System.out.println ("symbol:" + symbol + "size:" + size + "FONT:"
				+ Font );
	}
}


Then, we define a character factory class, through a Map<java.lang.character, character> to save the character object, use the character value to find out whether the character object has been created, and if the character object you are looking for already exists, then return the object directly , the character object instance is created instead.

//Flyweightfactory class class Characterfactory {private static map<character, icharacter> CHS
	= new Hashmap<character, icharacter> ();
	private static Characterfactory instance = new Characterfactory ();

	Single case mode private Characterfactory () {}; /** * Checked The character whether existed or not,if the character existed, then directly returns, otherwise, INS
	 Tantiates a character object.

		* @param key * @return/Public icharacter Getcharacter (Character key) {Icharacter Character = null;
		if (Chs.containskey (key)) {character = Chs.get (key);
				else {switch (Key.charvalue ()) {case ' A ': character = new Charactera ();
			Break
				Case ' B ': character = new Characterb ();
			Break
				Case ' C ': character = new Characterc ();
			Break
			Default:break;
		} chs.put (key, character);
	return character;
	public static Characterfactory getinstance () {return instance; }
}

Client code

Client public
class Flyweightclient {public

	static void Main (string[] args) {

		String text = "ABCABBCC"; 
  char[] CHS = Text.tochararray ();

		Characterfactory factory = Characterfactory.getinstance ();

		for (int i = 0; CHS!= null && i < chs.length; i++) {

			char ch = chs[i];
			Character key = character.valueof (CH);

			Icharacter character = Factory.getcharacter (key);
			Character.display ();}}


Applicable Scenarios

An application uses a large number of objects. Due to the use of a large number of objects, resulting in a large storage overhead. Most of the state of an object can become an external state. If you delete the external state of an object, you can replace many groups of objects with a relatively small number of shared objects. Applications do not rely on object identities.


flyweight need to pay attention to the problem

The object sharing method is used to reduce the number of objects in the system, thus reducing the memory pressure brought by fine-grained objects to the system. In the concrete realization aspect, we must pay attention to the object state processing, must correctly distinguish the object the internal state and the external state, this is realizes the privilege model the key.
The advantage of the privilege mode is that it drastically reduces the number of objects in memory. In order to do this, the element mode also paid a certain price:
In order for an object to be shared, it needs to externalized part of the state, which complicates the logic of the system. The pattern of the privilege is externalized part of the state of the object, while reading the external state makes the runtime longer.



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.