当一个复杂的对象的构造有许多可选参数的时候,就应该考虑使用构建器(Builder设计模式)来构建对象。
一般来说, Builder常常作为实际产品的静态内部类来实现(提高内聚性).
故而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(">>发动机>>");
}
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:>>车身>>>>轮子>>>>发动机>>>>座椅>>
Car caeTwo = new Car.Builder().withModel().withSeat().withWheel().build();
System.out.println("Car2 has: " + caeTwo);
//Car2 has: A car has:>>车身>>>>轮子>>>>座椅>>
}