Java design mode -- Flyweight)

Source: Internet
Author: User

Java design mode -- Flyweight)

In boxing, Flyweight refers to the most lightweight model, that is, "Fly magnitude" or "rainfall level". Here we use the free translation of "Enjoy yuan mode", because it can better reflect the intention of the model. The metadata mode is the object structure mode. The metadata mode supports a large number of fine-grained objects efficiently in a shared manner.
In JAVA, the String type uses the metadata mode. The String object is of the final type and cannot be changed once it is created. In JAVA, string constants exist in the 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.
Structure of the metadata mode:
The metadata mode uses a shared object to avoid overhead of a large number of objects with the same content. The most common and intuitive overhead is the memory loss. The key to enabling shared object sharing is to differentiate the Internal State and External State ).
The internal state is stored inside the object, and it will not change with the environment. Therefore, a shared object can have an internal state and can be shared.
The external state changes with the environment and cannot be shared. The external status of the object to be shared must be saved by the client. After the object is created, you can import the object to the original object as needed. The external State does not affect the inherent state of the object. They are independent of each other.
The metadata mode is dividedSimple meta-mode and compound meta-Mode
Simple metadata structure:
Examples/bSu7j2s + examples/examples + ofG + 38zlz + examples/Ws + nP88/examples/m55raos/examples + examples/samples/t1Kq21M/samples + 2ho7Wx0ru49r/Nu6e2y7bUz/ o199PD0ru49s/t1Kq21M/release + rdPQ0ru49rf7us/release + zdomtbhm4bmp 1ek49tl09c1xm/t1Kq21M/release/KyrXEz + 3 UqrbUz/release "brush: java; ">Public class ConcreteFlyweight implements Flyweight {private Character intrinsicState; public ConcreteFlyweight (Character state) {this. intrinsicState = state;}/*** the external state is used as a parameter to pass in the method, which changes the behavior of the method, but does not change the inherent state of the object */public void operation (String state) {System. out. println ("Intrinsic state =" + intrinsicState); System. out. println ("Extrinsic state =" + state );}}

You must note that the client cannot instantiate a specific metadata class directly. Instead, you must use a factory object to obtain a metadata object using a factory () method. Generally, the metadata factory has only one object in the system. Therefore, you can use the singleton mode.
When the client needs to simply enjoy the metadata object, it needs to call the factory () method of the metadata factory, and pass in the inherent state of the simple metadata object, which is generated by the factory method.

Public class FlyweightFactory {private Map
  
   
Files = new HashMap
   
    
(); Public Flyweight factory (Character state) {Flyweight fly = files. get (state); if (fly = null) {// if the object does not exist, create a new Flyweight object fly = new ConcreteFlyweight (state ); // put the new Flyweight object in the cache files. put (state, fly) ;}return fly ;}} /*** @ author Fu yuwei * @ time 10:52:51 * @ param args */public static void main (String [] args) {FlyweightFactory factory = new FlyweightFactory (); flyweight fly = factory. factory (new Character ('A'); fly. operation ("first call"); fly = factory. factory (new Character ('B'); fly. operation ("second call"); fly = factory. factory (new Character ('A'); fly. operation ("Third Call ");}
   
  

Although the client has applied for three metadata objects, there are only two actually created metadata objects. This is the meaning of sharing. The running result is as follows:

Compound metadata mode:

The roles involved in the composite meta-role are as follows:
  ● Abstract Flyweight role:An abstract interface is provided to specify the methods to be implemented for all specific meta-roles.
  ● Specific ConcreteFlyweight roles:Implement the interface specified by the abstract metadata role. If there is an inner state, it must provide storage space for the inner state.
  ● ConcreteCompositeFlyweight:Objects represented by a composite meta-object cannot be shared. However, a composite meta-object can be divided into multiple combinations of meta-objects. A composite meta-role is also called a shared meta object.
  ● FlyweightFactory role:This role is used to create and manage the role. This role must ensure that the object can be shared by the system. When a client object calls a metadata object, the metadata factory role checks whether a metadata object meets the requirements in the system. If you already have a metadata factory role, you should provide the existing metadata object. If the system does not have an appropriate metadata object, the metadata factory role should create a suitable metadata object.
  

Public class ConcreteCompositeFlyweight implements Flyweight {private Map
  
   
Files = new HashMap
   
    
(); /*** Add a new simple metadata object to the cluster * @ author Fu yuwei * @ time 11:20:08 * @ param key * @ param fly */public void add (Character key, flyweight fly) {files. put (key, fly);}/*** the external state is used as the parameter. */public void operation (String state) {Flyweight fly = null; for (Object o: files. keySet () {fly = files. get (o); fly. operation (state) ;}} public class FlyweightFactory {private Map
    
     
Files = new HashMap
     
      
();/*** Composite metadata factory Method * @ author Fu yuwei * @ time 11:24:51 * @ param compositeSate * @ return */public Flyweight factory (List
      
        CompositeSate) {ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight (); for (Character state: compositeSate) {compositeFly. add (state, this. factory (state);} return compositeFly;} public Flyweight factory (Character state) {Flyweight fly = files. get (state); if (fly = null) {// if the object does not exist, create a new Flyweight object fly = new ConcreteFlyweight (state ); // put the new Flyweight object in the cache files. put (state, fly); System. out. println ("the object is created") ;}return fly ;}}
      
     
    
   
  

Composite meta objects are composed of simple meta objects through composite. Therefore, they provide clustering management methods such as add. Because a composite object has different clustering elements, these elements are added after the composite object is created, which means that the state of the composite object will change, therefore, composite object cannot be shared.
The composite metadata role implements the interface specified by the abstract metadata role, that is, the operation () method. This method has a parameter that represents the external state of the composite metadata object. The external States of all elements of a compound object are the same as those of the compound object; the inherent states of a simple object in a compound object are generally not equal, otherwise there will be no use of value.
  

/*** @ Author Fu yuwei * @ time 10:52:51 * @ param args */public static void main (String [] args) {List
  
   
CompositeState = new ArrayList
   
    
(); CompositeState. add ('A'); compositeState. add ('B'); compositeState. add ('C'); compositeState. add ('A'); compositeState. add ('B'); FlyweightFactory flyFactory = new FlyweightFactory (); Flyweight compositeFly1 = flyFactory. factory (compositeState); Flyweight compositeFly2 = flyFactory. factory (compositeState); compositeFly1.operation ("composite call"); System. out. println ("Can shared objects in composite mode:" + (compositeFly1 = compositeFly2); Character state = 'a'; Flyweight fly1 = flyFactory. factory (state); Flyweight fly2 = flyFactory. factory (state); System. out. println ("whether the object can be shared in simple metadata mode:" + (fly1 = fly2 ));}
   
  


Advantages and disadvantages
The advantage of the Meta mode is that it greatly reduces the number of objects in the memory. However, it also pays a very high price to achieve this:
● The metadata mode makes the system more complex. In order for objects to be shared, some States need to be externalized, which complicate the logic of the program.
● The metadata mode externalizes the state of the object, and reads the external State to slightly extend the running time.

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.