/** * @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 is a pattern of shared components, here are some objects that need to be reused in the system, shared into a single component * * like JDBC database connection pool, thread pool, etc. are applied to the enjoy meta-mode * database connection pool: Create a certain number of connections, into the pool, use the time to take out, release and then deposit * Chicheng: Similar, also used to remove, release and then deposit * so there will generally be a set to store components There is a unit of the plant 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 a 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