Flyweight of the structure pattern (share yuan)

Source: Internet
Author: User
Tags abstract

Flyweight definition:
Avoid the overhead of a large number of small classes that have the same content (such as memory-intensive), so that you share a class (meta-Class).

why use?
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 of the common denominator of these object groups, a meta class is designed to encapsulate classes that can be shared, and some features are dependent on the application (context) and are not shareable, which also flyweight the internal state intrinsic of two important concepts and the extrinsic of external states.

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 flyweight is used for sharing, The Flyweight factory is responsible for maintaining an Flyweight pool (pattern pooling) object that holds the internal state.

Flyweight mode is a mode to improve the efficiency and performance of the program, which will greatly speed up the running 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, we can store these strings in the flyweight pool ( Pool).

How do I use it?

Let's start with the flyweight abstract interface:

public interface Flyweight
{
public void 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 Concreteflyweight implements Flyweight {
Private intrinsicstate State;
  
public void operation (Extrinsicstate state)
{
Specific operation
}

}

Of course, not all flyweight-specific implementations of subclasses need to be shared, so there is another concreteflyweight that is not shared:

public class Unsharedconcreteflyweight implements Flyweight {

public void 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, a new object is created, added to the pool, and returned to the object. Pool

public class Flyweightfactory {
Flyweight Pool
Private Hashtable flyweights = new Hashtable ();

Public Flyweight getflyweight (Object key) {

Flyweight Flyweight = (Flyweight) flyweights.get (key);

if (flyweight = = null) {
Create a new Concreteflyweight
Flyweight = new Concreteflyweight ();
Flyweights.put (key, flyweight);
}

return flyweight;
}
}

Now that the basic framework of the flyweight pattern is ready, let's see How to Invoke:

Flyweightfactory factory = new Flyweightfactory ();
Flyweight fly1 = factory.getflyweight ("Fred");
Flyweight fly2 = 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:
1. Date of the film (year)
2. Singers ' names and other information (artist)
3. Record tracks (title)

Among them, the singer's name may be repeated, that is, there may be several 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 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 class CD {

Private String title;
private int year;
Private Artist Artist;

Public String GetTitle () {return title;}
public int getYear () {return year; }
Public Artist getartist () {return Artist; }

public void Settitle (String t) {title = T;}
public void setyear (int y) {year = y;}
public void Setartist (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) {
name = N;
}

}

And look at flyweight factory, specifically designed to create the shareable concreteflyweight:artist above.

public class Artistfactory {

Hashtable pool = new Hashtable ();

Artist getartist (String key) {

Artist result;
result = (Artist) pool.get (key);
Create a new artist
if (result = = null) {
result = 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.

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.