Mode of design---pattern Flyweight

Source: Internet
Author: User

Definition of a pattern

The Flyweight pattern is an important implementation of Stoke technology, which is defined as follows:

Use sharing to support large numbers of fine-grained objects efficiently.

Use shared objects to effectively support a large number of fine-grained objects.

The definition of the enjoy meta-mode presents two requirements: fine-grained objects and shared objects. Allocating too many objects will compromise the performance of the program while also causing memory overflow. Avoiding this is the use of shared technologies in the enjoy meta-mode.

Fine-grained states are divided into internal states (instrinsic) and external states (extrinsic):
Internal state:
The internal state is the information that the object can share, stored inside the object of the privilege, and not changed as the environment changes, belonging to the shareable part.

External state:
An external state is a token that an object is dependent on, a state that is changed as the environment changes and cannot be shared.

Type

Structure class

Usage Scenarios for patterns
    • A large number of similar objects exist in the system
    • Fine-grained objects have a closer external state, and the internal state is independent of the environment, meaning that the object does not have a specific identity.
    • Scenarios that require a buffer pool
Advantages and Disadvantages

Enjoy meta mode is a very simple mode, it can greatly reduce the object created by the application, reduce the use of program memory, enhance the performance of the program, but it also improves the complexity of the system, the need to separate external and internal state, and the external state has the curing characteristics, should not be changed with the internal state changes, Otherwise, the logic of the system is confusing.

Introduction to UML class diagram roles
    • flyweight-abstract enjoy meta role

It is simply an abstract class that defines an interface or implementation of an object's external state and internal state.

    • concreteflyweight-specific enjoy meta role

Specific product classes, this role should be noted that the internal state processing should be environment-independent, should not occur an operation to change the internal state, while modifying the external state, which is absolutely not allowed.

    • Unsharedconcreteflyweight-a non-shareable shared meta role

An object that does not have an external state or that does not require the ability to use a shared technology is typically not present in the enjoy meta factory.

    • flyweightfactory-Factory

Constructs a pool container, providing a way to get objects from the pool.

The purpose of the enjoy meta-mode is to use the sharing technology, so that some fine-grained objects can be shared, the use of fine-grained objects, easy to reuse or refactor.

The common source of the pattern

Flyweight:

 Public Abstract  class Flyweight {    //Internal state    PrivateString Instrinsic;//External status    Private FinalString extrinsic;//require the access to the Meta role to accept the external state     Public Flyweight(String extrinsic) {Super(); This. extrinsic = extrinsic; } PublicStringGetinstrinsic() {returnInstrinsic; } Public void Setinstrinsic(String instrinsic) { This. instrinsic = Instrinsic; }//define business logic     Public Abstract void operate();@Override     PublicStringtoString() {return "Flyweight [instrinsic="+ Instrinsic +", extrinsic="+ Extrinsic +"]"; }}

CONCRETEFLYWEIGHT1:

publicclass ConcreteFlyweight1 extends Flyweight {    publicConcreteFlyweight1(String extrinsic) {        super(extrinsic);        // TODO Auto-generated constructor stub    }    @Override    publicvoidoperate() {        // TODO Auto-generated method stub        System.out.println("ConcreteFlyweight1----operate()");    }}

ConcreteFlyweight2:

publicclass ConcreteFlyweight2 extends Flyweight {    publicConcreteFlyweight2(String extrinsic) {        super(extrinsic);        // TODO Auto-generated constructor stub    }    @Override    publicvoidoperate() {        // TODO Auto-generated method stub        System.out.println("ConcreteFlyweight2----operate()");    }}

Flyweightfactory:

Import Java.util.HashMap; Public classflyweightfactory {//Create a pool container    Private StaticHashmap<string, flyweight> pool =NewHashmap<string, flyweight> ();//Enjoy the Yuan factory     Public StaticFlyweightGetflyweight(String extrinsic) {Flyweight Flyweight =NULL;if(Pool.containskey (extrinsic)) {flyweight = pool.Get(extrinsic); }Else{flyweight =NewCONCRETEFLYWEIGHT1 (extrinsic);        Pool.put (extrinsic, flyweight); }returnFlyweight }//The information in the Print pool container     Public Static void Printpool(){ for(inti =0; I < pool.size (); i++) {System. out. println (":"+pool.Get("Indext:"+i)); }    }}

Client:

 Public classClient { Public Static void Main(string[] args) {//TODO auto-generated method stubFlyweight Flyweight =NULL; for(inti =0; I <3; i++) {flyweight = Flyweightfactory.getflyweight ("Indext:"+i);        Flyweight.operate ();        } flyweightfactory.printpool (); System. out. println ("------------------------"); for(inti =0; I <3; i++) {flyweight = Flyweightfactory.getflyweight ("Indext:"+i);        Flyweight.operate ();    } flyweightfactory.printpool (); }}

Output Result:

ConcreteFlyweight1----operate()ConcreteFlyweight1----operate()ConcreteFlyweight1----operate():Flyweight [instrinsic=null, extrinsic=indext:0]:Flyweight [instrinsic=null, extrinsic=indext:1]:Flyweight [instrinsic=null, extrinsic=indext:2]------------------------ConcreteFlyweight1----operate()ConcreteFlyweight1----operate()ConcreteFlyweight1----operate():Flyweight [instrinsic=null, extrinsic=indext:0]:Flyweight [instrinsic=null, extrinsic=indext:1]:Flyweight [instrinsic=null, extrinsic=indext:2]

From the results, we can see that the buffer method of pool technology does not increase the number of flyweight.

Mode implementation in Android source code
Zatan

Resources

(1). Zen of Design mode-28th chapter enjoy meta-mode
(2) Enjoy meta mode
Https://github.com/simple-android-framework/android_design_patterns_analysis/tree/master/flyweight

Mode of design---pattern Flyweight

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.