Use
enjoy meta mode (Singleton)
Use shared technology to effectively support a large number of fine-grained objects.
structure
Graph-Enjoy meta-mode structure diagram
flywight : It is the superclass or interface of all the specific classes of the class, through which the Flyweight can accept and act on the external state.
AbstractclassFlyweight {
PublicAbstractvoidOperation (intExtrinsicstates);
}
concreteflyweight : is to inherit the Flyweight superclass or implement the Flyweight interface, and increase the storage space for the internal state.
classConcreteflyweightextendsFlyweight {
@Override
PublicvoidOperation (intExtrinsicstates) {
SYSTEM.OUT.PRINTLN ("Shared flyweight:" + extrinsicstates);
}
}
unsharedconcreteflyweight : Refers to Flyweight subclasses that do not need to be shared, because Flyweight interface sharing is possible, but it does not force sharing.
classUnsharedconcreteflyweightextendsFlyweight {
@Override
PublicvoidOperation (intExtrinsicstates) {
System.out.println ("Flyweight not shared:" + extrinsicstates);
}
}
flywightfactory: Is a Flyweight factory that is used to create and manage the object. It is primarily used to ensure that Flyweight is reasonably shared, and when a user requests a Flyweight, the Flyweightfactory object provides a created instance or creates one (if the object does not exist).classflywightfactory {
Privatehashtable<string, flyweight> flyweights =NewHashtable<string, flyweight> ();
PublicFlywightfactory () {
Flyweights.put ("X",NewConcreteflyweight ());
Flyweights.put ("Y",NewConcreteflyweight ());
Flyweights.put ("Z",NewConcreteflyweight ());
}
PublicFlyweight getflyweight (String key) {
return((Flyweight) Flyweights.get (key));
}
}
Test Code:
PublicclassFlyweightpattern {
PublicStaticvoidMain (string[] args) {
intExtrinsicstates = 1;
Flywightfactory factory =NewFlywightfactory ();
Flyweight FX = Factory. Getflyweight ("X");
Fx. Operation (Extrinsicstates);
Flyweight FY = factory. Getflyweight ("Y");
Fy. Operation (++extrinsicstates);
Flyweight FZ = Factory. Getflyweight ("Z");
Fz. Operation (++extrinsicstates);
Flyweight uf =NewUnsharedconcreteflyweight ();
uf. Operation (++extrinsicstates);
}
}
JAVA design mode to enjoy meta mode