Java share mode/enjoy meta mode (Flyweight mode)

Source: Internet
Author: User

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 " To find common ground among these object groups, design a meta-class, encapsulate the classes that can be shared, and, in addition, some features that depend on the application (context), are not shareable, This also flyweight 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 we 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, create a new object, join the pool, and then return the pool of objects that were sent out. 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;
}
At this point, 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 applies to data sources such as XML we have already mentioned that when a large number of strings are read from the data source, there must be 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. Out date (year)
    2. Singers ' names and other information (artist)
    3. 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 has only 3 CDs, CDS can be seen as a large number of repetitions because there are only three fields in it, and there are duplicates (singers ' names).

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 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:artistpublic 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.
Enjoy meta mode Overview
    Use shared technology to effectively support a large number of fine-grained objects.
Applicability
    Use flyweight mode when all of the following are available:    1. An application uses a large number of objects.    2. Due to the use of a large number of objects, resulting in a large storage overhead.    3. Most of the state of an object can become an external state.    4. If you delete an object's external state, you can replace many group objects with a relatively small number of shared objects.    5. The application does not depend on the object identity. Because flyweight objects can be shared, the identity test returns true for objects that are conceptually distinct.
participants
    1.Flyweight      describes an interface that Flyweight can accept and act on an external state through this interface.      The 2.ConcreteFlyweight implements the flyweight interface and increases storage space for internal states, 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.    3.UnsharedConcreteFlyweight      Not all flyweight sub-classes need to be shared. A flyweight interface makes sharing possible, but it does not force sharing.      at certain levels of the flyweight object structure, Unsharedconcreteflyweight objects typically use Concreteflyweight objects as child nodes.    4.FlyweightFactory      Create and manage flyweight objects.      ensure that flyweight is properly shared. When the user requests a flyweight, the Flyweightfactory object provides a created instance or creates one (if it does not exist).
class Diagram Example Flyweight
Public interface Flyweight {    void action (int arg);}
Concreteflyweight
public class Flyweightimpl implements Flyweight {public    void action (int arg) {        //TODO auto-generated Method St UB        System.out.println ("parameter value:" + arg);}    }
flyweightfactory
public class Flyweightfactory {    private static Map flyweights = new HashMap ();        Public flyweightfactory (String Arg) {        flyweights.put (ARG, New Flyweightimpl ());    }        public static Flyweight Getflyweight (String key) {        if (flyweights.get (key) = = null) {            flyweights.put (key, New Fly Weightimpl ());        }        return Flyweights.get (key);    }        public static int GetSize () {        return flyweights.size ();}    }
Test
public class Test {public    static void Main (string[] args) {        //TODO auto-generated method stub        Flyweight fly1 = Flyweightfactory.getflyweight ("a");        Fly1.action (1);                Flyweight fly2 = Flyweightfactory.getflyweight ("a");        System.out.println (fly1 = = fly2);                Flyweight fly3 = flyweightfactory.getflyweight ("b");        Fly3.action (2);                Flyweight fly4 = flyweightfactory.getflyweight ("C");        Fly4.action (3);                Flyweight fly5 = flyweightfactory.getflyweight ("D");        Fly4.action (4);                System.out.println (Flyweightfactory.getsize ());}    }
result
Parameter value: 1true parameter value: 2 parameter value: 3 parameter value: 44


Java share mode/enjoy meta mode (Flyweight mode)

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.