當(dāng)一個復(fù)雜的對象的構(gòu)造有許多可選參數(shù)的時候,就應(yīng)該考慮使用構(gòu)建器(Builder設(shè)計模式)來構(gòu)建對象。

Paste_Image.png
一般來說, Builder常常作為實際產(chǎn)品的靜態(tài)內(nèi)部類來實現(xiàn)(提高內(nèi)聚性).
故而Product,Director, Builder常常是在一個類文件中, 例如本例中的Car.java.
public class Car {
// 這邊就隨便定義幾個屬性
private boolean addModel;
private boolean addWheel;
private boolean addEngine;
private boolean addSeat;
public Car(Builder builder) {
this.addModel = builder.addModel;
this.addWheel = builder.addWheel;
this.addEngine = builder.addEngine;
this.addSeat = builder.addSeat;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("A car has:");
if (this.addModel) {
builder.append(">>車身>>");
}
if (this.addWheel) {
builder.append(">>輪子>>");
}
if (this.addEngine) {
builder.append(">>發(fā)動機>>");
}
if (this.addSeat) {
builder.append(">>座椅>>");
}
return builder.toString();
}
public static class Builder {
private boolean addModel;
private boolean addWheel;
private boolean addEngine;
private boolean addSeat;
public Builder() {
}
public Builder withModel() {
this.addModel = true;
return this;
}
public Builder withWheel() {
this.addWheel = true;
return this;
}
public Builder withEngine() {
this.addEngine = true;
return this;
}
public Builder withSeat() {
this.addSeat = true;
return this;
}
public Car build() {
return new Car(this);
}
}
public static void main(String[] args) {
// build car
Car carOne = new Car.Builder().withModel().withModel().withEngine().withSeat().withWheel().build();
System.out.println("Car1 has: " + carOne);
//Car1 has: A car has:>>車身>>>>輪子>>>>發(fā)動機>>>>座椅>>
Car caeTwo = new Car.Builder().withModel().withSeat().withWheel().build();
System.out.println("Car2 has: " + caeTwo);
//Car2 has: A car has:>>車身>>>>輪子>>>>座椅>>
}