background image

21

  Flyweight flyweight = (Flyweight) flyweights.get(obj);

//----------------2

22
23

  

if

(flyweight == 

null

) ...{

//---------------------------------------------------3

24
25

  //产生新的 ConcreteFlyweight

26
27

  flyweight = 

new

 ConcreteFlyweight((String)obj);

28
29

  flyweights.put(obj, flyweight);

//--------------------------------------5

30
31

  }

32
33

  

return

 flyweight;

//---------------------------------------------------------6

34
35

  }

//end GetFlyWeight(...)

36
37

  

public

 

int

 getFlyweightSize()

38
39

  ...

40
41

  {

42
43

  

return

 flyweights.size();

44
45

  }

46
47

  }

//end class FlyweightFactory

48
49

  这个工厂方法类非常关键,这里详细解释一下:

 

   在 1 处定义了一个 Hashtable 用来存储各个对象;在 2 处选出要实例化的对象,在 6 处
将该对象返回,如果在 Hashtable

 

中没有要选择的对象, 此时变量 flyweight 为 null,产生

一个新的 flyweight 存储在 Hashtable 中,并将该对象返回。
  最后看看 Flyweight 的调用:

1

 

package

 Flyweight;

2
3

  

import

 java.util.Hashtable;

4
5

  

public

 

class

 FlyweightPattern ...{

6
7

  FlyweightFactory factory = 

new

 FlyweightFactory();

8