java设计模式:Java设计模式的工厂思路方法模式(图)

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

2、 工厂思路方法模式角色和结构

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

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

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

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

  

   3、个简单例子

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

   4、工厂思路方法模式和简单工厂模式

  工厂思路方法模式和简单工厂模式再结构上区别不是很明显工厂思路方法类核心是个抽象工厂类而简单工厂模式把核心放在个具体类上

  工厂思路方法模式的所以有个别名叫多态性工厂模式是具体工厂类都有共同接口或者有共同抽象父类

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

  工厂思路方法模式退化后可以演变成简单工厂模式

Tags:  java设计模式chm java设计模式pdf java设计模式

延伸阅读

最新评论

发表评论