Java 设计模式之建造者模式
概述
- 定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
- 优点:具体的建造者类之间是相互独立的,容易扩展。由于具体的建造者是独立的,因此可以对建造过程逐步细化,而不对其他的模块产生任何影响。
UML图
- Director:指挥者类,用于统一组装过程。
- Builder:抽象Builder类,规范产品的组建。
- ConcreteBuilder:具体Builder类,实现抽象Builder类中的方法,并返回一个组建好的对象。
- Product:产品类。
简单实现
产品类:
public class Computer {
private String mainboard;
private String cpu;
private String memory;
// 省略get/set/toString方法
}
抽象Builder类:
public abstract class Builder {
public abstract void buildMainboard(String mainboard);
public abstract void buildCpu(String cpu);
public abstract void buildMemory(String memory);
public abstract Computer create();
}
具体Builder类:
public class DivComputerBuilder extends Builder {
private Computer computer = new Computer();
@Override
public void buildMainboard(String mainboard) {
computer.setMainboard(mainboard);
}
@Override
public void buildCpu(String cpu) {
computer.setCpu(cpu);
}
@Override
public void buildMemory(String memory) {
computer.setMemory(memory);
}
@Override
public Computer create() {
return computer;
}
}
指挥者类:
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public Computer createComputer(String mainboard, String cpu, String memory) {
builder.buildMainboard(mainboard);
builder.buildCpu(cpu);
builder.buildMemory(memory);
Computer computer = builder.create();
return computer;
}
}
使用:
public class Client {
public static void main(String[] args) {
Builder builder = new DivComputerBuilder();
Director director = new Director(builder);
Computer computer = director.createComputer("技嘉", "amd", "金士顿");
System.out.println(computer);
}
}
输出:
Computer{mainboard='技嘉', cpu='amd', memory='金士顿'}
优化建造者模式
public class Computer {
private String mainboard;
private String cpu;
private String memory;
private Computer() {
}
@Override
public String toString() {
return "Computer{" +
"mainboard='" + mainboard + '\'' +
", cpu='" + cpu + '\'' +
", memory='" + memory + '\'' +
'}';
}
public static Builder build() {
return new Builder();
}
public static class Builder {
private Computer computer;
private Builder() {
computer = new Computer();
}
public Builder buildMainboard(String mainboard) {
computer.mainboard = mainboard;
return this;
}
public Builder buildCpu(String cpu) {
computer.cpu = cpu;
return this;
}
public Builder buildMemory(String memory) {
computer.memory = memory;
return this;
}
public Computer create() {
return computer;
}
}
}
使用:
Computer computer = Computer.build()
.buildMainboard("技嘉")
.buildCpu("AMD")
.buildMemory("金士顿")
.create();
System.out.println(computer);
输出:
Computer{mainboard='技嘉', cpu='AMD', memory='金士顿'}