设计一个Pizza店,Pizza的制作过程为:createPizza( )——>orderPizza( ),其中createPizza()又由prepare,bake,cut,box四个过程组成。Pizza的种类也有多种。
整个关系图如下:
下面是用户点一个CheesePizza后的时序图:
全部代码如下:
1 package SimpleFactory;
2
3 public class Main
4 {
5
6 public static void main(String[] args)
7 {
8 PizzaStore store = new PizzaStore();
9 store.createPizza("Cheese");
10 store.orderPizza();
11 }
12 }
13
1 package SimpleFactory;
2
3 public class PizzaStore
4 {
5
6 private Pizza mPizza;
7
8 public Pizza orderPizza()
9 {
10 mPizza.prepare();
11 mPizza.bake();
12 mPizza.cut();
13 mPizza.box();
14 return mPizza;
15 }
16
17 public Pizza createPizza(String pizzaName)
18 {
19 if (pizzaName.equals("Cheese"))
20 {
21 mPizza = new CheesePizza();
22 System.out.println("CheesPizza created.");
23 }
24 else if (pizzaName.equals("ClamPizza"))
25 {
26 mPizza = new ClamPizza();
27 System.out.println("ClamPizza created.");
28 }
29 return mPizza;
30 }
31 }
32
33
我们看到PizzaStore类中的19~28行,出现了if...else if...,当又有新的Pizza品种时,显然这个createPizza函数免不了再加一个else if...
按照设计模式的原则,我们希望PizzaStore这个类整体保持固定,把变化的部分封装出去:
其结论就是用一个新的类来专门负责new 各种类型的实体——这个新类就是SimpleFactory:
到PizzaStore点一个CheesePizza的流程如下:
相比原代码,需变动PizzaStore的createPizza方法,还有新增一个PizzaFactory类:
1 package SimpleFactory;
2
3 public class PizzaStore
4 {
5
6 private PizzaFactory mPizzaFactory;
7 private Pizza mPizza;
8
9 public Pizza orderPizza()
10 {
11 mPizza.prepare();
12 mPizza.bake();
13 mPizza.cut();
14 mPizza.box();
15 return mPizza;
16 }
17
18 public Pizza createPizza(String pizzaName)
19 {
20 mPizzaFactory = new PizzaFactory();
21 mPizza = mPizzaFactory.factoryPizzaCreation(pizzaName);
22 return mPizza;
23 }
24 }
25
26
1 package SimpleFactory;
2
3 public class PizzaFactory
4 {
5
6 private Pizza mPizza;
7
8 public Pizza factoryPizzaCreation(String pizzaName)
9 {
10 if (pizzaName.equals("CheesePizza"))
11 {
12 mPizza = new CheesePizza();
13 System.out.println("CheesPizza created.");
14 }
15 else if (pizzaName.equals("ClamPizza"))
16 {
17 mPizza = new ClamPizza();
18 System.out.println("ClamPizza created.");
19 }
20 return mPizza;
21 }
22
23
24 }
25
26
可见,所谓的Simple Factory的实质就是:
问题:可能根据不同条件返回同一种类型的不同结果,且该条件在不断的变化中,我们需要封装这种变化。(不仅仅是encapsulate object creation)
结论:写一个专门的类,该类中的一个方法来实现上面的条件判断。