将一个复杂的对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示。
我在这里以电脑组装为例
public class Computer {
private String cpu;
private String mainBoard;
private String gpu;
private String power;
private String memory;
private String hardDisk;
private String radiator;
private String box;
/*省略get和set方法,请自行添加*/
@Override
public String toString() {
return "Computer{" +
"cpu='" + cpu + '\'' +
", mainBoard='" + mainBoard + '\'' +
", gpu='" + gpu + '\'' +
", power='" + power + '\'' +
", memory='" + memory + '\'' +
", hardDisk='" + hardDisk + '\'' +
", radiator='" + radiator + '\'' +
", box='" + box + '\'' +
'}';
}
}
public abstract class Builder {
public Computer computer = new Computer();
public abstract void buildCpu();
public abstract void buildMainBoard();
public abstract void buildGpu();
public abstract void buildPower();
public abstract void buildMemory();
public abstract void buildHardDisk();
public abstract void buildRadiator();
public abstract void buildBox();
public abstract Computer installComputer();
}
public class ComputerBuilder extends Builder {
@Override
public void buildCpu() {
computer.setCpu("AMD R5 5800X");
}
@Override
public void buildMainBoard() {
computer.setMainBoard("msi B550 MORTAR");
}
@Override
public void buildGpu() {
computer.setGpu("RTX3060");
}
@Override
public void buildPower() {
computer.setPower("鑫谷650W");
}
@Override
public void buildMemory() {
computer.setMemory("Kingston DDR4 8GB * 4");
}
@Override
public void buildHardDisk() {
computer.setHardDisk("SAMSUNG SSD NVMe 500G m.2");
}
@Override
public void buildRadiator() {
computer.setRadiator("九州风神水冷");
}
@Override
public void buildBox() {
computer.setBox("淘宝挑个自己喜欢的");
}
@Override
public Computer installComputer() {
return computer;
}
}
public class Installer {
private Builder builder;
public Installer(Builder builder){
this.builder = builder;
}
public Computer assembly(){
builder.buildCpu();
builder.buildBox();
builder.buildGpu();
builder.buildHardDisk();
builder.buildMainBoard();
builder.buildMemory();
builder.buildPower();
builder.buildRadiator();
return builder.installComputer();
}
}
public class Client {
public static void main(String[] args) {
Installer installer = new Installer(new ComputerBuilder());
Computer computer = installer.assembly();
System.out.println(computer.toString());
}
}
结果
Computer{cpu='AMD R5 5800X', mainBoard='msi B550 MORTAR', gpu='RTX3060', power='鑫谷650W', memory='Kingston DDR4 8GB * 4', hardDisk='SAMSUNG SSD NVMe 500G m.2', radiator='九州风神水冷', box='淘宝挑个自己喜欢的'}