Design Pattern pocket edition continuous Reprint-flyweight (enjoy yuan)

Source: Internet
Author: User

Original: fanix

Flyweight definition:
Avoid the overhead of a large number of small classes with the same content (such as memory consumption), so that everyone can share a class (Meta class ).

Why?
The principle of object-oriented language is that everything is an object, but if it is used, sometimes the number of objects may appear very large. For example, if the word processing software uses every text as an object, there are thousands of words, and the number of objects is several thousand, which undoubtedly consumes memory. Therefore, we still need to "seek the same ground while reserving differences" to find out what these object groups have in common and design a metadata class, encapsulate classes that can be shared. In addition, some features depend on the application context and cannot be shared. In flyweight, the two important concepts are internal states intrinsic and external States extrinsic.

To put it bluntly, we need to first create an original model and then generate a specific model with different characteristics in different scenarios and environments. Obviously, we need to generate different new objects here, therefore, the factory mode is often used in the flyweight mode. the internal state of Flyweight is used for sharing. flyweight factory is responsible for maintaining a flyweight pool (mode pool) to store internal State objects.

The flyweight mode is a mode for improving program efficiency and performance, which greatly speeds up program running. there are many applications: for example, if you want to read a series of strings from a database and many of these strings are repeated, we can store these strings in the flyweight pool.

How to use it?

Let's start with the flyweight abstract interface:

Program code:

  1. Public InterfaceFlyweight
  2. {
  3.   Public VoidOperation (extrinsicstate State );
  4. }
  5. // The abstract data type used in this mode (self-designed)
  6. Public InterfaceExtrinsicstate {}

 

The following figure shows the specific implementation of the interface (concreteflyweight) and increases the memory space for the internal status. concreteflyweight must be shareable and must be saved in any internal status (intrinsic). That is to say, concreteflyweight must be independent of its application environment.
Program code:

  1. Public ClassConcreteflyweightImplementsFlyweight {
  2.   PrivateIntrinsicstate state;
  3.   
  4.   Public VoidOperation (extrinsicstate state)
  5. {
  6.       // Specific operation
  7. }
  8. }

 

Of course, not all flyweight implementation subclasses need to be shared, so there is another non-shared concreteflyweight:
Program code:

  1. Public ClassUnsharedconcreteflyweightImplementsFlyweight {
  2.   Public VoidOperation (extrinsicstate state ){}
  3. }

Flyweight factory is responsible for maintaining a flyweight pool (storing the internal status). When the client requests a shared flyweight, the factory first searches whether the pool is applicable. If yes, factory simply returns and sends this object. Otherwise, it creates a new object, adds it to the pool, and then returns the object. pool

Program code:

  1. Public ClassFlyweightfactory {
  2.   // Flyweight pool
  3.   PrivateHashtable flyweights =NewHashtable ();
  4.   PublicFlyweight getflyweight (ObjectKey ){
  5. Flyweight = (flyweight) flyweights. Get (key );
  6.     If(Flyweight =Null){
  7.       // Generate a new concreteflyweight
  8. Flyweight =NewConcreteflyweight ();
  9. Flyweights. Put (Key, flyweight );
  10. }
  11.     ReturnFlyweight;
  12. }
  13. }

 

Now, the basic framework of the flyweight mode is ready. Let's look at how to call it:
Program code:

  1. Flyweightfactory factory =NewFlyweightfactory ();
  2. Flyweight fly1 = factory. getflyweight ("Fred ");
  3. Flyweight fly2 = factory. getflyweight ("Wilma ");
  4. ......

From the call point of view, it seems like a pure factory use, but the secret lies in the internal design of the factory.

The flyweight mode is applied to XML and other data sources.
As we have mentioned above, when a large number of strings are read from the data source, there must be duplicates among them, we can use the flyweight mode to improve efficiency. Take the recording CD as an example. In an XML file, stores multiple CD files.

Each CD has three fields:
1. Release date (year)
2. The Creator's name and other information (artist)
3. recording tracks (title)

The Creator's name may be repeated, that is, there may be multiple CDs of different tracks of the same artist in different periods. we use "creator name" as the shared concreteflyweight. the other two fields are used as unsharedconcreteflyweight.

First, let's take a look at the content of the XML file of the Data source:

Program code:

<? 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 there are only three CD examples in the above example, CD can be considered as a large number of repeated sub-classes, because there are only three fields in the example, and there are repeated (publisher name ).

CD is similar to the above interface flyweight:

Program code:

  1. Public ClassCd {
  2.   Private StringTitle;
  3.   Private IntYear;
  4.   PrivateArtist;
  5.   Public StringGettitle (){ReturnTitle ;}
  6.   Public IntGetyear (){ReturnYear ;}
  7.   PublicArtist getartist (){ReturnArtist ;}
  8.   Public VoidSettitle (StringT) {Title = T ;}
  9.   Public VoidSetyear (IntY) {year = y ;}
  10.   Public VoidSetartist (artist a) {artist = ;}
  11. }

Use "creator name" as the shared concreteflyweight:
Program code:

  1. Public ClassArtist {
  2.   // Internal status
  3.   Private StringName;
  4.   // Note that artist is immutable.
  5.   StringGetname (){ReturnName ;}
  6. Artist (StringN ){
  7. Name = N;
  8. }
  9. }

 

Let's take a look at the flyweight factory, which is specifically used to make the above shareable concreteflyweight: artist
Program code:

  1. Public ClassArtistfactory {
  2. Hashtable pool =NewHashtable ();
  3. Artist getartist (StringKey ){
  4. Artist result;
  5. Result = (artist) pool. Get (key );
  6.     //// Generate a new artist
  7.     If(Result =Null){
  8. Result =NewArtist (key );
  9. Pool. Put (Key, result );
  10.       
  11. }
  12. ReturnResult;
  13. }
  14. }

 

When you have thousands or even more CDs, the flyweight mode will save more space. The more shared flyweight, the larger the space savings.

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.