/** * @author Stone * */public class Letter {private string name;public letters (String name) {this.name = name;} Public String GetName () {return name;}}
/** * A plant that produces a letter object (Singleton factory) * @author Stone * */public class Letterfactory {private map<string, letter> map;private s Tatic Letterfactory instance = new Letterfactory ();p rivate letterfactory () {map = new hashmap<string, letter> ();} public static Letterfactory getinstance () {return instance;} public void Add (letter) {if (letter! = null &&!map.containskey (Letter.getname ())) {Map.put ( Letter.getname (), letter);} System.out.println ("map.size====" + map.size ());} Public letter Get (String name) {return map.get (name);}}
/* * Flyweight mode structured mode The main purpose is to realize the sharing of objects * literally a pattern of shared elements, here are some objects that need to be reused in the system. Share as a single component * * database connection pooling, such as JDBC database connection pool, thread pool, etc. are applied to the pool of connections: A certain number of connections have been created. Into the pool. To be removed when used. Re-deposit on release * Chicheng: Similar, is also used to remove, release and then deposit * so there will generally be a set to store components. There is a facility for the management of components.*/public class Test {public static void main (string[] args) {Letterfactory factory = Letterfactory.getinstance (); String Word = "easiness"; Addletterbyname (factory, word); Getletter (factory, Word);} Add the letter object static void Addletterbyname (Letterfactory factory, String Word) {for (char C:word.tochararray ()) {Factory.add (n EW Letter (c + ""));}} Output letter Object static void Getletter (Letterfactory factory, String Word) {for (char C:word.tochararray ()) {System.out.println ( Factory.get (c + ""));}}}
Print
Map.size====1map.size====2map.size====2map.size====3map.size====4map.size====5map.size====5[email protected][ Email protected][email protected][email protected][email protected][email protected][email protected]
Java implementation of the enjoy meta (Flyweight) mode