The enjoy meta-mode can be understood as a cache of objects, and all objects are managed by building a single-element factory.
The code is as follows:
- Flyweight the interface of the sharing element
Public Interface Flyweight { publicvoid doAction ();}
- Flyweightimpl specific shared class implementations
Public class Implements flyweight{ @Override publicvoid doAction () { System.out.println ("doAction");} }
Public classFlyweightfactory {Private StaticMap<string, flyweight>flyweights=NewHashmap<string, flyweight>(); Public StaticFlyweight getflyweight (String key) {if(Flyweights.get (key) = =NULL) {flyweights.put (key,NewFlyweightimpl ()); } return(Flyweight) flyweights.get (key); } Public Static intGetSize () {returnflyweights.size (); }}
Public class App { publicstaticvoid main (string[] args) { new flyweightfactory (); Factory.getflyweight ("a"). DoAction (); Factory.getflyweight ("B"). DoAction (); Factory.getflyweight ("a"). DoAction (); System.out.println (Factory.getsize ());} }
doactiondoactiondoaction2
design mode (enjoy meta mode)