Design mode-Enjoy meta mode

Source: Internet
Author: User

Enjoy meta mode (English: Flyweight pattern) is a software design pattern. It uses shared objects to minimize memory usage and to share information to as many similar objects as possible, and it is suitable for a large number of objects that are simply duplicated to use an unacceptable amount of memory. Usually part of the state in an object can be shared. It is common practice to put them in an external data structure and pass them on to the element when it is needed.

Define the FlyWeight mode, and use sharing technology to effectively support a large number of fine-grained objects. Structuretwo statesThe intrinsic state is stored in the inside of the element, and it does not change with the environment, it is a sharable state that can not be shared, it changes with the change of environment, so the external state is maintained by the client (because the change of environment is caused by the client). UML structure diagram (1) Abstract enjoy meta role: for the specific enjoy meta-role defined must be implemented method, the outer state is in the form of parameters passed through this method. In Java, it can be assumed by an abstract class, an interface. (2) Specific privileges: The method of implementing the abstract role stipulation. If there is an intrinsic state, it is responsible for providing storage space for the intrinsic state. (3) Enjoy the meta-factory role: responsible for creating and managing the rewards role. To achieve the purpose of sharing, the role of the implementation is the key! (4) Client role: maintains a reference to all of the object's objects, and also needs to store the corresponding external state. Usage scenarios If an application uses a large number of objects, and these objects cause significant storage overhead, you can consider whether you can use the enjoy meta mode.  For example, if you find that an object has generated a large number of fine-grained instances, and these instances are essentially the same except for a few parameters, if you move those shared parameters outside the class and pass them in as method calls, you can share the number of large individual instances by sharing them. Example

Explain the concept: that is, if there are multiple identical objects in a system, it is possible to share only one copy, without having to instantiate an object each. For example, a text system, each letter set an object, then the big lowercase letters are altogether 52, then you need to define 52 objects. If there is a 1M of text, then the letter is much more, if each letter is defined an object then the memory is already exploded. So if you share an object with each letter, you save a lot of resources.
In flyweight mode, Factory mode is often present in the flyweight (enjoy meta) mode because of the variety of objects to be produced. The internal state of the Flyweight is used for sharing, and Flyweight factory is responsible for maintaining an object storage pool (Flyweight pool) to hold the internal state of the object. 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 a lot of applications, here's an example:

First, define an abstract flyweight class:

Package Flyweight;  Public abstract class Flyweight
{public abstract void operation (); } 

Implement a specific class:

Package Flyweight;  public class Concreteflyweight extends flyweight{  private string string, public  concreteflyweight (String str) {   string = str;  } public  void operation ()  {  System.out.println ("Concrete---Flyweight:" + string);  }  }  

Implement a factory method class:

Package Flyweight;  Import java.util.Hashtable;  public class flyweightfactory{  private Hashtable flyweights = new Hashtable ();//----------------------------1  Public  flyweightfactory () {} public  Flyweight getflyweight (Object obj) {  Flyweight Flyweight = (Flyweight) Flyweights.get (obj);//----------------2  if (flyweight = = null) {//--------------------------------------------   -------3  //generates a new concreteflyweight  flyweight = "Concreteflyweight" ((String) obj);  Flyweights.put (obj, flyweight);//--------------------------------------5  }  return flyweight;//-------- -------------------------------------------------6  } public  int getflyweightsize () {  return Flyweights.size ();  }  }  

This factory method class is very critical, here is a detailed explanation:
A hashtable is defined at 1 to store each object, the object to instantiate at 2, the object is returned at 6, and if there are no objects to select in Hashtable, the variable flyweight is null. Produces a new flyweight stored in the Hashtable and returns the object.
Finally look at the invocation of flyweight:

Package Flyweight;  Import java.util.Hashtable;    public class flyweightpattern{Flyweightfactory factory = new Flyweightfactory ();   Flyweight fly1;   Flyweight Fly2;   Flyweight Fly3;   Flyweight Fly4;   Flyweight fly5;   Flyweight Fly6; /** *//** Creates a new instance of Flyweightpattern */public Flyweightpattern () {fly1 = Factory.getflyweight ("Googl    E ");    Fly2 = Factory.getflyweight ("Qutr");    Fly3 = Factory.getflyweight ("Google");    Fly4 = Factory.getflyweight ("Google");    Fly5 = Factory.getflyweight ("Google");   Fly6 = Factory.getflyweight ("Google");    } public void Showflyweight () {fly1.operation ();    Fly2.operation ();    Fly3.operation ();    Fly4.operation ();    Fly5.operation ();    Fly6.operation ();    int objSize = Factory.getflyweightsize ();   System.out.println ("objSize =" + objSize);    } public static void Main (string[] args) {System.out.println ("the FlyWeight pattern!");    Flyweightpattern fp = new Flyweightpattern ();  Fp.showflyweight (); }  }   

Here is the result of the operation:

Concrete---flyweight:google  concrete---flyweight:qutr  concrete---flyweight:google  Concrete---flyweight:google  concrete---flyweight:google  concrete---flyweight:google  objSize = 2  

We have defined 6 objects, 5 of which are the same, according to the definition of flyweight mode "Google" should share an object, in the actual number of objects we can see that the actual object is only 2.

Summarize:
Flyweight (enjoy meta) mode is so important because it helps you to save a lot of memory space in a complex system. In the Java language, the string type is the use of the enjoy meta pattern. The string object is the final type, and the object cannot be changed once it is created. In Java, where string constants are present in a constant pool, Java ensures that a string constant has only one copy in the constant pool. String a= "abc", where "abc" is a string constant.

Familiar with Java should know the following example:

String a = "Hello";  String b = "Hello";  if (a = = b)  System.out.println ("OK");  else  System.out.println ("Error");  

The output is: OK. You can see that the IF condition compares the addresses of two A and B, or memory space.
The core summary is that the objects that can be shared, that is, the same type of objects returned are actually the same instance, when the client asks to generate an object, the factory detects if there is an instance of this object, and if it exists then returns this object instance directly, and if it does not exist, creates one and saves it, which means some singleton patterns. Usually the factory class will have a member variable of the collection type to hold the object, such as Hashtable,vector. In Java, the database connection pool, the thread pool, and so on are the applications that use the enjoy meta-mode.

Design mode-Enjoy meta mode

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.