建造者模式是一种创建型设计模式,它允许您分步骤创建复杂对象。该模式特别适用于当一个对象需要经过多个步骤才能创建完成时。建造者模式将对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。
public class Computer {
private String cpu;
private String ram;
private String storage;
private Computer(ComputerBuilder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.storage = builder.storage;
}
public static class ComputerBuilder {
private String cpu;
private String ram;
private String storage;
public ComputerBuilder setCpu(String cpu) {
this.cpu = cpu;
return this;
}
public ComputerBuilder setRam(String ram) {
this.ram = ram;
return this;
}
public ComputerBuilder setStorage(String storage) {
this.storage = storage;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}