1掺喻、建造者模式的定義
將復雜對象的構建和表示分離開,使得相同的構建順序可以實現不同的表示
2感耙、建造者模式的實現要點
3抑月、應用場景
多個部件或零件,都可以裝配到一個對象中(某個類的構造函數入參多于3個谦絮,且包含可選參數)
相同的方法,不同的執(zhí)行順序性锭,會產生不同的結果
4叫胖、實現舉例
public class Computer {
private String cpu;
private String ram;
private String mouse;//可選
private String keyboard;//可選
private String display;//可選
private Computer(Builder builder){
this.cpu = builder.cpu;
this.ram = builder.ram;
this.mouse = builder.mouse;
this.keyboard = builder.keyboard;
this.display = builder.display;
}
public static class Builder{
private String cpu;
private String ram;
private String mouse;//可選
private String keyboard;//可選
private String display;//可選
public Builder(String cpu,String ram){
this.cpu = cpu;
this.ram = ram;
}
public Builder setMouse(String mouse) {
this.mouse = mouse;
return this;
}
public Builder setKeyboard(String keyboard){
this.keyboard = keyboard;
return this;
}
public Builder setDisplay(String display){
this.display = display;
return this;
}
public Computer build(){
return new Computer(this);
}
}
public static void main(String[] args) {
Computer computer = new Computer.Builder("intel", "samsung")
.setMouse("logic")
.setKeyboard("logical")
.setDisplay("Lenovo")
.build();
}
}