您的位置:首页 > 编程语言 > Java开发

Java设计模式之工厂方法模式

2009-02-26 21:01 579 查看
一 、工厂方法(Factory Method)模式

  工厂方法模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。

  二、 工厂方法模式角色与结构

  抽象工厂(Creator)角色:是工厂方法模式的核心,与应用程序无关。任何在模式中创建的对象的工厂类必须实现这个接口。

  具体工厂(Concrete Creator)角色:这是实现抽象工厂接口的具体工厂类,包含与应用程序密切相关的逻辑,并且受到应用程序调用以创建产品对象。在上图中有两个这样的角色:BulbCreator与TubeCreator。

  抽象产品(Product)角色:工厂方法模式所创建的对象的超类型,也就是产品对象的共同父类或共同拥有的接口。在上图中,这个角色是Light。

  具体产品(Concrete Product)角色:这个角色实现了抽象产品角色所定义的接口。某具体产品有专门的具体工厂创建,它们之间往往一一对应。

  


  三、一个简单的实例

1 // 产品 Plant接口
2
3   public interface Plant { }
4
5   //具体产品PlantA,PlantB
6
7   public class PlantA implements Plant {
8
9   public PlantA () {
10
11   System.out.println("create PlantA !");
12
13   }
14
15   public void doSomething() {
16
17   System.out.println(" PlantA do something ...");
18
19   }
20
21   }
22
23   public class PlantB implements Plant {
24
25   public PlantB () {
26
27   System.out.println("create PlantB !");
28
29   }
30
31   public void doSomething() {
32
33   System.out.println(" PlantB do something ...");
34
35   }
36
37   }
38
39   // 产品 Fruit接口
40
41   public interface Fruit { }
42
43   //具体产品FruitA,FruitB
44
45   public class FruitA implements Fruit {
46
47   public FruitA() {
48
49   System.out.println("create FruitA !");
50
51   }
52
53   public void doSomething() {
54
55   System.out.println(" FruitA do something ...");
56
57   }
58
59   }
60
61   public class FruitB implements Fruit {
62
63   public FruitB() {
64
65   System.out.println("create FruitB !");
66
67   }
68
69   public void doSomething() {
70
71   System.out.println(" FruitB do something ...");
72
73   }
74
75   }
76
77   // 抽象工厂方法
78
79   public interface AbstractFactory {
80
81   public Plant createPlant();
82
83   public Fruit createFruit() ;
84
85   }
86
87   //具体工厂方法
88
89   public class FactoryA implements AbstractFactory {
90
91   public Plant createPlant() {
92
93   return new PlantA();
94
95   }
96
97   public Fruit createFruit() {
98
99   return new FruitA();
100
101   }
102
103   }
104
105   public class FactoryB implements AbstractFactory {
106
107   public Plant createPlant() {
108
109   return new PlantB();
110
111   }
112
113   public Fruit createFruit() {
114
115   return new FruitB();
116
117   }
118
119   }
120
121

  四、工厂方法模式与简单工厂模式

  工厂方法模式与简单工厂模式再结构上的不同不是很明显。工厂方法类的核心是一个抽象工厂类,而简单工厂模式把核心放在一个具体类上。

  工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口,或者有共同的抽象父类。

  当系统扩展需要添加新的产品对象时,仅仅需要添加一个具体对象以及一个具体工厂对象,原有工厂对象不需要进行任何修改,也不需要修改客户端,很好的符合了"开放-封闭"原则。而简单工厂模式在添加新产品对象后不得不修改工厂方法,扩展性不好。

  工厂方法模式退化后可以演变成简单工厂模式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: