定义
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
用户只需指定需要建造的类型就可以得到它们,建造过程及细节不需要知道
类型
创建型
适用场景
如果一个对象有非常复杂的内部结构(很多属性)
想把复杂对象的创建和使用分离
优缺点
优点
封装性好,创建和使用分离
扩展性好、建造类之间独立、一定程度上解耦
缺点
产生多余的 Builder对象产品内部发生变化
建造者都要修改,成本较大
代码分析
常见的连续调用
代码实现,构造静态内部类,调用后返回自身
实现代码
package site.gaox.design.patterns.creational.builder.V2;
/**
* @Description: <p> </p>
* @Auther: gaox·Eric
* @Date: 2019/3/18 15:16
*/
public class Computer {
private String CPU;
private String memory;
private String SSD;
private String power;
private String mainboard;
public Computer(ComputerBuilder computerBuilder) {
this.CPU = computerBuilder.CPU;
this.memory = computerBuilder.memory;
this.SSD = computerBuilder.SSD;
this.power = computerBuilder.power;
this.mainboard = computerBuilder.mainboard;
}
@Override
public String toString() {
return "Computer{" +
"CPU='" + CPU + '\'' +
", memory='" + memory + '\'' +
", SSD='" + SSD + '\'' +
", power='" + power + '\'' +
", mainboard='" + mainboard + '\'' +
'}';
}
public static class ComputerBuilder {
private String CPU;
private String memory;
private String SSD;
private String power;
private String mainboard;
/**
* 还可以做默认值设置
* @param CPUName
* @return
*/
public ComputerBuilder buildCPU(String CPUName) {
this.CPU = CPUName;
return this;
}
public ComputerBuilder buildMemory(String memoryName) {
this.memory = memoryName;
return this;
}
public ComputerBuilder buildSSD(String SSDName) {
this.SSD = SSDName;
return this;
}
public ComputerBuilder buildPower(String PowerName) {
this.power = power;
return this;
}
public ComputerBuilder buildMainboard(String mainboardName) {
this.mainboard = mainboardName;
return this;
}
//最后调用本方法也可以返回这个对象
public Computer build() {
return new Computer(this);
}
}
}