建造者模式
目录
为什么要使用建造者模式
建造者模式将对象本身和对象的创建进行解耦,用户不需要知道对象创建的细节和流程
建造者模式解决了对象的创建过程和流程,这些都不需要用户关心
建造者和工厂模式不同的是建造者更加关系构建对象的流程,各个部件的构建顺序,而工厂模式更加关心的是对象的整体,工厂模式创建的对象比较单一,没有很复杂的组件,而如果对象由好几个对象组成,并且对象属性比较多,构建顺序有一定的要求则需要使用建造者模式
实现
创建一个电脑
public class Computer {
private String brand;
private String cpu;
private String mainBoard;
private String hardDisk;
private String displayCard;
private String power;
private String memory;
// 省略 getter, setter, toString
}
Builder抽象类
public abstract class Builder {
protected Computer computer = new Computer();
public abstract void buildBrand();
public abstract void buildCPU();
public abstract void buildMainBoard();
public abstract void buildHardDisk();
public abstract void buildDisplayCard();
public abstract void buildPower();
public abstract void buildMemory();
public Computer createComputer() {
return computer;
}
}
具体的实现
public class DellComputerBuilder extends Builder {
@Override
public void buildBrand() {
computer.setBrand("Dell电脑");
}
@Override
public void buildCPU() {
computer.setCpu("i5-8300H 四核");
}
@Override
public void buildMainBoard() {
computer.setMainBoard("戴尔主板");
}
@Override
public void buildHardDisk() {
computer.setHardDisk("1T + 128GB SSD");
}
@Override
public void buildDisplayCard() {
computer.setDisplayCard("GTX1060 独立6GB");
}
@Override
public void buildPower() {
computer.setPower("4芯 锂离子电池 180W AC适配器");
}
@Override
public void buildMemory() {
computer.setMemory("4G + 4G");
}
}
指挥协调创建对象的Director
类,此类可以省略,直接在具体的Builder
类上加一个construct
方法也可
//构建过程的指挥者
public class ComputerDirector {
public Computer construct(Builder builder) {
Computer computer;
builder.buildBrand();
builder.buildCPU();
builder.buildDisplayCard();
builder.buildHardDisk();
builder.buildMainBoard();
builder.buildMemory();
builder.buildPower();
computer = builder.createComputer();
return computer;
}
}
使用
public static void main(String[] args) {
ComputerDirector director = new ComputerDirector();
Computer dellComputer = director.construct(new DellComputerBuilder());
System.out.println(dellComputer.getBrand());
Computer asuComputer = director.construct(new ASUComputerBuilder());
System.out.println(asuComputer.getBrand());
}
}