Skip to content

Commit 3f02ce6

Browse files
committed
增加 README
1 parent e6b7f6d commit 3f02ce6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

factory-method/README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# 工厂方法 ( Factory Method )
2+
3+
## 用途
4+
5+
> 定义一个用于创建对象的接口, 让子类决定实例化哪一个类。 Factory Method使一个类的
6+
实例化延迟到其子类
7+
8+
## 别名
9+
10+
> 虚构造器 ( Virtual Constructor )
11+
12+
## 实例
13+
14+
> 假定现在有两个厨师,一个只会做中餐,另一个只会做西餐,餐品分为熟食和生食两类。顾客需要顾客需要根据自己的口味来选择对应的厨师并告知其需要熟食还是生食,厨师根据顾客的口味来进行烹制
15+
16+
## 模式分析
17+
18+
> 在基于类的设计中,工厂方法模式通常作为创建模式来使用。它使用工厂方法来处理创建对象的过程,无需指定创建对象的确切类型。客户端通过调用工厂方法来创建对象,这里的方法是在接口中指定的,或是由子类实现的,或是由基类实现,或者通过子类进行方法覆盖,从头至尾无需调用具体类的构造函数
19+
>
20+
> 以厨师为例,首先定义厨师和食物两个接口
21+
22+
```
23+
public interface Cook {
24+
Food cookFood(FoodType foodType);
25+
}
26+
27+
public interface Food {
28+
FoodType getFoodType();
29+
}
30+
```
31+
32+
> 定义食物的枚举类型
33+
```
34+
public enum FoodType {
35+
HOT("热的"), COLD("凉的");
36+
private String name;
37+
FoodType(String foodType) {
38+
this.name = foodType;
39+
}
40+
public String getName() {
41+
return name;
42+
}
43+
}
44+
```
45+
46+
> 定义两种厨师的实现类,分别负责西餐和中餐的烹饪工作
47+
```
48+
public class WesternCook implements Cook {
49+
public Food cookFood(FoodType foodType) {
50+
return new WesternFood(foodType);
51+
}
52+
}
53+
54+
public class ChineseCook implements Cook {
55+
public Food cookFood(FoodType foodType) {
56+
return new ChineseFood(foodType);
57+
}
58+
}
59+
```
60+
> 生成食物对象时只需调用厨师对象的工厂方法即可
61+
```
62+
Cook cook1 = new WesternCook();
63+
Cook cook2 = new ChineseCook();
64+
Food food1 = cook1.cookFood(FoodType.COLD);
65+
Food food2 = cook2.cookFood(FoodType.HOT);
66+
```
67+
68+
## 适用场景
69+
70+
>* 当一个类不知道它所必须创建的对象的类的时候
71+
>* 当一个类希望由它的子类来指定它所创建的对象的时候
72+
>* 当类将创建对象的职责委托给多个帮助子类中的某一个, 并且你希望将哪一个帮助子类是代理者这一信息局部化的时候

0 commit comments

Comments
 (0)