文章目录
  1. 构造器模式

构造器模式

  • 将一个复杂对象的构建与它的表示分离,使同样的构建过程可以创建不同的表示
    Builder
  • 构造器的使用者,构建过程的持有方(算法)
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
public interface Director {
void constuct(PhoneBuilder builder);
}
//制作一个手机
public class PhoneDirector implements Director {
public void constuct(PhoneBuilder builder){
builder.buildCamera();
builder.buildEarphone();
builder.buildScreen();
}
}
//打包两个手机
public class PhoneBoxDirector implements Director {
@Override public void constuct(PhoneBuilder builder) {
builder.buildCamera();
builder.buildCamera();
builder.buildEarphone();
builder.buildEarphone();
builder.buildScreen();
builder.buildScreen();
}
}
  • 手机构造器builder
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
public interface PhoneBuilder {
void buildScreen();
void buildEarphone();
void buildCamera();
String getResult();
}
public class ApplePhoneBuilder implements PhoneBuilder {
private int screenCount;
private int earPhoneCount;
private int cameraCount;
@Override public void buildScreen() {
System.out.println("构建苹果屏幕");
screenCount++;
}
@Override public void buildEarphone() {
System.out.println("构建苹果耳机");
earPhoneCount++;
}
@Override public void buildCamera() {
System.out.println("构建苹果摄像头");
cameraCount++;
}
@Override public String getResult() {
return "苹果手机构建完成,组件数量:"+screenCount+" "+earPhoneCount+" "+cameraCount;
}
}
public class SamsungPhoneBuilder implements PhoneBuilder {
private int screenCount;
private int earPhoneCount;
private int cameraCount;
@Override public void buildScreen() {
System.out.println("构建三星屏幕");
screenCount++;
}
@Override public void buildEarphone() {
System.out.println("构建三星耳机");
earPhoneCount++;
}
@Override public void buildCamera() {
System.out.println("构建三星摄像头");
cameraCount++;
}
@Override public String getResult() {
return "三星手机构建完成,组件数量:" + screenCount + " " + earPhoneCount + " " + cameraCount;
}
}
  • 客户端
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
public class App {
/**
* 构建器模式,将对象的构建(对象的构造顺序或策略)与表示分离
* @param args
*/
public static void main(String[] args) {
PhoneBuilder appleBuilder=new ApplePhoneBuilder();
PhoneBuilder samsungPhoneBuilder=new SamsungPhoneBuilder();
PhoneBuilder[] builders={appleBuilder,samsungPhoneBuilder};
//第一种构建的策略
Director direct1=new PhoneDirector();
for(int i=0;i<builders.length;i++){
direct1.constuct(builders[i]);//这里是构建的方法,而不存储构建的结果
System.out.println(builders[i].getResult());//构建的结果由具体的构造器返回
}
//第二种构建的策略
Director direct2=new PhoneBoxDirector();
for(int i=0;i<builders.length;i++){
direct2.constuct(builders[i]);//这里是构建的方法,而不存储构建的结果
System.out.println(builders[i].getResult());//构建的结果由具体的构造器返回
}
}
}
文章目录
  1. 构造器模式