1: //享元工厂(FlyweightFactory)角色
2: import java.util.Map;
3: import java.util.HashMap;
4: import java.util.Iterator;
5:
6: public class FlyweightFactory
7: { 8: private HashMap flies = new HashMap();
9: /**
10: * @link aggregation
11: * @directed
12: * @clientRole Flyweights
13: */
14: private Flyweight lnkFlyweight;
15:
16: public FlyweightFactory(){} 17:
18: public Flyweight factory(String compositeState)
19: { 20: ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
21:
22: int length = compositeState.length();
23: Character state = null;
24:
25: for(int i = 0; i < length; i++)
26: { 27: state = new Character(compositeState.charAt(i) );
28: System.out.println("factory(" + state + ")"); 29: compositeFly.add( state, this.factory( state) );
30: }
31: return compositeFly;
32: }
33:
34: public Flyweight factory(Character state)
35: { 36: if ( flies.containsKey( state ) )
37: { 38: return (Flyweight) flies.get( state );
39: }
40: else
41: { 42: Flyweight fly = new ConcreteFlyweight( state );
43: flies.put( state , fly);
44: return fly;
45: }
46: }
47:
48: public void checkFlyweight()
49: { 50: Flyweight fly ;
51: int i = 0 ;
52:
53: System.out.println("\n==========checkFlyweight()============="); 54: for ( Iterator it = flies.entrySet().iterator() ; it.hasNext() ; )
55: { 56: Map.Entry e = (Map.Entry) it.next();
57: System.out.println( "Item " + (++i) + " : " + e.getKey());
58: }
59: System.out.println("\n==========checkFlyweight()============="); 60: }
61:
62: }
63: