Effective Java

2 创建和销毁对象

image-20240603234949006


  • Builder模式简单示例

Builder模式是一种创建型设计模式,它允许你将对象的构建过程与表示分离,从而可以创建具有不同表示的复杂对象。以下是一个简单的Builder模式示例,以构建一个计算机为例:

首先,定义一个Computer类作为产品(Product):

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
public class Computer {
private String cpu;
private String ram;
private String hdd;
private String graphicsCard;

// Private constructor to prevent direct instantiation from outside
private Computer(ComputerBuilder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.hdd = builder.hdd;
this.graphicsCard = builder.graphicsCard;
}

// Getters (no setters since we want immutability)

public String getCpu() {
return cpu;
}

public String getRam() {
return ram;
}

public String getHdd() {
return hdd;
}

public String getGraphicsCard() {
return graphicsCard;
}

// Inner static Builder class
public static class ComputerBuilder {
private String cpu;
private String ram;
private String hdd;
private String graphicsCard;

public ComputerBuilder() {}

public ComputerBuilder setCpu(String cpu) {
this.cpu = cpu;
return this;
}

public ComputerBuilder setRam(String ram) {
this.ram = ram;
return this;
}

public ComputerBuilder setHdd(String hdd) {
this.hdd = hdd;
return this;
}

public ComputerBuilder setGraphicsCard(String graphicsCard) {
this.graphicsCard = graphicsCard;
return this;
}

public Computer build() {
return new Computer(this);
}
}
}

接下来,你可以使用ComputerBuilder来创建Computer对象,同时利用链式调用来使代码更简洁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
public static void main(String[] args) {
Computer computer = new Computer.ComputerBuilder()
.setCpu("Intel i7")
.setRam("16GB DDR4")
.setHdd("1TB SSD")
.setGraphicsCard("NVIDIA RTX 3080")
.build();

System.out.println("Built Computer with specs: ");
System.out.println("CPU: " + computer.getCpu());
System.out.println("RAM: " + computer.getRam());
System.out.println("HDD: " + computer.getHdd());
System.out.println("Graphics Card: " + computer.getGraphicsCard());
}
}

在这个例子中,ComputerBuilder负责逐步构建一个Computer实例,而实际的构建逻辑和表示(即具体的组件)是分离的。这不仅让代码更加清晰,也提供了更好的灵活性,因为你可以轻松地修改或扩展构建过程。




----------- 本文结束 -----------




0%