建造者模式

建造者模式(Builder Pattern),将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

Class Diagram

Implementation

具体产品

1
2
3
4
5
6
7
8
9
10
11
12
public class Computer {
List<String> components = new ArrayList<String>();

public void add(String component){
components.add(component);
}

public void display(){
System.out.println("个人电脑,组成如下:\n--------------");
components.forEach((System.out::println));
}
}

建造者抽象类

1
2
3
4
5
6
abstract class Builder {
public abstract void buildCPU();
public abstract void buildGPU();
public abstract void buildPower();
public abstract Computer build();
}

具体建造者

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
public class StandardComputer extends Builder {

private Computer computer = new Computer();

@Override
public void buildCPU() {
computer.add("处理器");
}

@Override
public void buildGPU() {
computer.add("显卡");
}

@Override
public void buildPower() {
computer.add("电源");
}

@Override
public Computer build() {
return computer;
}
}

public class MyComputer extends Builder{

private Computer computer = new Computer();

@Override
public void buildCPU() {
computer.add("AMD 2600x");
}

@Override
public void buildGPU() {
computer.add("GTX 2060");
}

@Override
public void buildPower() {
computer.add("爱国者 1250w");
}

@Override
public Computer build() {
return computer;
}
}

指挥者

1
2
3
4
5
6
7
8
public class Director {

public void construct(Builder builder){
builder.buildCPU();
builder.buildGPU();
builder.buildPower();
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BuilderTest {

@Test
public void test() throws Exception{
Director director = new Director();

Builder standardBuilder = new StandardComputer();
Builder myBuilder = new MyComputer();

director.construct(standardBuilder);
Computer standardComputer = standardBuilder.build();
standardComputer.display();

director.construct(myBuilder);
Computer myComputer = myBuilder.build();
myComputer.display();
}
}

Example

Refence