Flyweight definition: Avoid the overhead of a large number of small classes that have the same content (such as memory consumption), so that you share a class (meta-Class).
Why use shared mode/enjoy meta mode
The principle of object-oriented language is that everything is an object, but if you really use it, sometimes the number of objects may seem very large, for example, word processing software, if each text as an object, thousands of words, the number of objects is thousands of, no doubt consumes memory, then we still want to "disagree", Find out what these object groups have in common, design a meta-class, encapsulate the classes that can be shared, and, in addition, some features that depend on the application (context) and are not shareable, which also flyweight the two important concepts of internal state intrinsic and external state extrinsic.
White point, is to pinch a primitive model, and then with different circumstances and environment, and then produce each characteristic of the concrete model, it is obvious that here need to produce different new objects, so flyweight pattern often appear Factory mode. The internal state of the Flyweight is used for sharing, and Flyweight factory is responsible for maintaining an object that has a Flyweight pool (pattern pools) to hold the internal state.
Flyweight mode is a mode to improve the efficiency and performance of the program, which will greatly speed up the operation of the program. There are many applications: for example, if you want to read a series of strings from a database, many of which are duplicates, then we can store these strings in the flyweight pool.
How to use shared mode/enjoy meta mode
Let's start with the flyweight abstract interface:
Public Interface flyweight{ publicvoid operation (extrinsicstate state); // abstract data types for this pattern (self-designed) Public Interface Extrinsicstate {}
The following is the implementation of the interface (Concreteflyweight), and the internal state to increase the memory space, the concreteflyweight must be shareable, it can save any state must be internal (intrinsic), that is, Concreteflyweight must be independent of its application environment.
Public class Implements Flyweight { private intrinsicstate state; Public void operation (extrinsicstate state) { // specific action }}
Of course, not all flyweight-specific implementations of subclasses need to be shared, so there is another concreteflyweight that is not shared:
Public class Implements Flyweight { publicvoid operation (extrinsicstate state) {}}
Flyweight Factory is responsible for maintaining a Flyweight pool (storage internal state), when the client requests a shared Flyweight, this factory first search in the pool is already applicable, if there is, factory simply return to send this object , otherwise, create a new object, join the pool, and then return the pool of objects that were sent out.
Public classFlyweightfactory {//Flyweight Pool PrivateHashtable flyweights =NewHashtable (); PublicFlyweight getflyweight (Object key) {Flyweight Flyweight=(Flyweight) flyweights.get (key); if(Flyweight = =NULL) {//Create a new concreteflyweightFlyweight =Newconcreteflyweight (); Flyweights.put (key, flyweight); }returnflyweight;}}
Now that the basic framework of the flyweight pattern is ready, let's see How to Invoke:
New= factory.getflyweight ("Fred"= Factory.getflyweight ("Wilma" );
From the call, it seems to be a purely factory use, but the secret lies in the internal design of factory.
Flyweight mode is applied in data sources such as XML
As we have mentioned above, when a large number of strings are read from the data source, and there are certainly duplicates, then we can use the flyweight mode to improve efficiency, in the case of CD CDs, in an XML file, storing data from multiple CDs.
Each CD has three fields:
- Out date (year)
- Singers ' names and other information (artist)
- Record Track (title)
Among them, the singer's name may be repeated, that is, there may be many different stages of the same singer's different tracks of the CD. We use the "vocalist name" as a shareable concreteflyweight. The other two fields are used as unsharedconcreteflyweight.
First look at the contents of the data source XML file:
<?XML version= "1.0"?><Collection><CD><title>Another Green world</title>< Year>1978</ Year><artist>Eno, Brian.</artist></CD><CD><title>Greatest Hits</title>< Year>1950</ Year><artist>Holiday, Billie</artist></CD><CD><title>Taking Tiger Mountain (by Strategy)</title>< Year>1977</ Year><artist>Eno, Brian.</artist></CD>.......</Collection>
Although the above example CD only 3, CD can be regarded as a large number of repetitions of the small class, because there are only three fields, and there are duplicates (singers name).
The CD is similar to the above interface Flyweight:
Public classCD {PrivateString title;Private intYear ;PrivateArtist Artist; PublicString GetTitle () {returntitle;} Public intGetYear () {returnYear ;} PublicArtist Getartist () {returnartist;} Public voidSettitle (String t) {title =T;} Public voidSetyear (intY) {year =y;} Public voidSetartist (Artist a) {Artist =A;}}
Use "vocalist name" as a shareable concreteflyweight:
Public class Artist { // internal state private String name; // Note that Artist is immutable. String GetName () {return name;} Artist (String N) { = n; }}
And look at flyweight factory, specifically designed to create the shareable concreteflyweight:artist above.
Public class new= (Artist) pool.get (key); //// generates a new Artistifnull new Artist (key); Pool.put (Key,result); } return result;} }
When you have thousands of or more CDs, the flyweight mode will save more space and the more flyweight you share, the greater the space savings will be.
Java share mode/enjoy meta mode (Flyweight mode)