Factory method pattern

概念

定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。

举例

使用了工厂方法模式,最大的优点就是当我们需要一个类对象时,只需要通过将我们需要的条件告诉具体的实现工厂,工厂就会返回给我们需要的对象,将对象封装在工厂中。同时,当具体产品类型增加时,我们只需定义该类,并告诉工厂我们想要该类对象,工厂就会自动帮我们创建。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Created by Heiku on 2018/7/27
*/
// 手机组件
abstract class PhoneComponents{

}

// 摄像头
class CameraComponent extends PhoneComponents{

CameraComponent(){
System.out.println("get cameraComponent");
}
}

// 屏幕
class ScreenComponent extends PhoneComponents{

ScreenComponent(){
System.out.println("get screenComponent");
}
}

// 处理器
class ProcessorComponent extends PhoneComponents{

ProcessorComponent(){
System.out.println("get prodcessorComponent");
}
}

// 工厂接口
interface Factory{

<T extends PhoneComponents> T createComponent(Class<T> clazz);
}


// 实际工厂
class ComponentFactory implements Factory{

@Override
public <T extends PhoneComponents> T createComponent(Class<T> clazz) {
try {
return clazz.newInstance();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}

// 手机零件店
public class PhoneShop {

public static void main(String[] args) {

Factory factory = new ComponentFactory();

// 我需要摄像头组件
factory.createComponent(CameraComponent.class);

// 我需要屏幕组件
factory.createComponent(ScreenComponent.class);

// 我需要处理器组件
factory.createComponent(ProcessorComponent.class);
}

}