建造者模式简介
这个设计模式就是代码世界的DIY(Do It Yourself)
,和现实生活中的DIY
是一个道理。比如说,我们需要一台能打游戏的高性能电脑,游戏发烧友通常不会购买市面上的电脑成品,而是自己选购零部件进行组装。
对于这种结构相对固定,但属性可灵活搭配组装的对象,就很适合使用建造者模式,它的特点就是可以对目标对象进行高度自由的定制化。
建造者模式实现
实现方式有多种,这里给出最常见的一种代码范例,还是拿组装电脑举例:
public class Computer {
private String cpu; // 处理器
private String gpu; // 显卡
private String ram; // 内存
private String ssd; // 硬盘
private String monitor; // 显示器
private String other; // 其它
Computer(String cpu, String gpu, String ram, String ssd, String monitor, String other) {
this.cpu = cpu;
this.gpu = gpu;
this.ram = ram;
this.ssd = ssd;
this.monitor = monitor;
this.other = other;
}
public static ComputerBuilder builder() {
return new ComputerBuilder();
}
public String toString() {
return "Computer(cpu=" + this.cpu + ", gpu=" + this.gpu + ", ram=" + this.ram + ", ssd=" + this.ssd + ", monitor=" + this.monitor + ", other=" + this.other + ")";
}
// 建造者:该设计模式的核心
public static class ComputerBuilder {
private String cpu;
private String gpu;
private String ram;
private String ssd;
private String monitor;
private String other;
ComputerBuilder() {
}
public ComputerBuilder cpu(String cpu) {
this.cpu = cpu;
return this;
}
public ComputerBuilder gpu(String gpu) {
this.gpu = gpu;
return this;
}
public ComputerBuilder ram(String ram) {
this.ram = ram;
return this;
}
public ComputerBuilder ssd(String ssd) {
this.ssd = ssd;
return this;
}
public ComputerBuilder monitor(String monitor) {
this.monitor = monitor;
return this;
}
public ComputerBuilder other(String other) {
this.other = other;
return this;
}
public Computer build() {
return new Computer(this.cpu, this.gpu, this.ram, this.ssd, this.monitor, this.other);
}
public String toString() {
return "Computer.ComputerBuilder(cpu=" + this.cpu + ", gpu=" + this.gpu + ", ram=" + this.ram + ", ssd=" + this.ssd + ", monitor=" + this.monitor + ", other=" + this.other + ")";
}
}
}
使用方法:
public static void main(String[] args) {
Computer computer = Computer.builder()
.cpu("Intel i5-14600KF")
.gpu("NVIDIA GeForce GTX 1060")
.ram("HOF Pro D5-7000MHz 16G*2")
.ssd("M.2 NVMe SSD")
.monitor("LG 27GP95U 27英寸4K 160Hz(超频) 游戏电竞显示器")
.other("其它配件")
.build();
System.out.println(computer);
}
建造者ComputerBuilder
天然具备代理层的性质,所以使用的时候,也可以在其中加入额外的代理逻辑。
如果项目中依赖了Lombok
工具,那么建造者模式代码将会更加简洁:
import lombok.Builder;
import lombok.ToString;
@Builder // 一个注解就能搞定
@ToString
public class Computer {
private String cpu; // 处理器
private String gpu; // 显卡
private String ram; // 内存
private String ssd; // 硬盘
private String monitor; // 屏幕
private String other; // 其它
}
使用方法和前面的一样,没有任何区别。实际上,前面的Computer
类代码就是使用Lombok
工具生成的最终类代码。