Enjoy meta mode (flyweight)
When it is necessary to have a lot of exactly the same or similar objects that need to be created, it is mostly similar when we can use the enjoy meta mode. Create as few objects as possible, saving memory.
There are 4 main characters in the enjoy meta model
1. The factory of the yuan
2. Abstract enjoy meta objects
2. Internal state object: can be shared
3. External state object: cannot be shared
The following is a chess piece for example: Each piece is an object, but the majority of each piece is the same, only the color, placement is not the same, so there is no need for each piece to create an object, the same and different separate.
//enjoy meta-class abstraction Public InterfaceFlyWeight {voidsetcolor (String color); String GetColor (); voidDiplay (Waibu c); }//internal, can be shared separated out, referencing external not to be sharedclassNeibuImplementsflyweight{PrivateString color; PublicNeibu (String color) { This. color =color; } Public voidsetcolor (String color) { This. color =color; } PublicString GetColor () {returncolor; } Public voidDiplay (Waibu c) {System.out.println ("Pawn Color" +color); System.out.println ("Pawn" +c.getx () + ":" +c.gety ()); } }//external, can not be shared separated outclasswaibu{PrivateString x; PrivateString y; PublicWaibu (string x, string y) { This. x =x; This. y =y; } PublicString GetX () {returnx; } Public voidSetX (String x) { This. x =x; } PublicString GetY () {returny; } Public voidsety (String y) { This. y =y; }
//enjoy the Yuan factory Public classFlyweightfactory {Private Staticmap<string, flyweight> map =NewHashmap<string, flyweight>(); Public StaticFlyWeight Get (String color) {if(Map.get (color)! =NULL){ returnmap.get (color); }Else{FlyWeight FlyWeight=NewNeibu (color); Map.put (color, flyWeight); returnFlyWeight; } } }
Public Static void Main (string[] args) { = Flyweightfactory.get ("white"); = Flyweightfactory.get ("white"); F1.diplay (new Waibu ("+")); F2.diplay (new Waibu ("" "," "") ") ;
White and white is actually an object without creating two, position can be defined by external state
Java design mode--Enjoy meta mode