构建器模式当然是自由裁量的,如果它过于复杂那就过于复杂了,你可能需要考虑一种不同的方式来创建对象,比如工厂模式。我认为构建器模式在以下几种情况下表现出色:
- 创建具有多个有效配置的对象
- 创建不可变对象,其中并非所有必需的数据都可以预先提供
以下是如何实现汽车制造商的一个示例:
public class Car {
private final boolean hasSunroof;
private final Color color;
private final int horsePower;
private final String modelName;
private Car(Color color, int horsePower, String modelName, boolean hasSunroof) {
this.color = color;
this.horsePower = horsePower;
this.hasSunroof = hasSunroof;
this.modelName = modelName;
}
public static Builder builder(Color color, int horsePower) {
return new Builder(color, horsePower);
}
public static class Builder {
private final Color color;
private final int horsePower;
private boolean hasSunroof;
private String modelName = "unknown";
public Builder(Color color, int horsePower) {
this.color = color;
this.horsePower = horsePower;
}
public Builder withSunroof() {
hasSunroof = true;
return this;
}
public Builder modelName(String modelName) {
this.modelName = modelName;
return this;
}
public Car createCar() {
return new Car(color, horsePower, modelName, hasSunroof);
}
}
}
Builder 不一定是嵌套类,但它确实允许您向可能滥用您的 API 的人隐藏您的构造函数。另请注意,必须提供最低限度的必需参数才能创建构建器。你可以像这样使用这个构建器:
Car car = Car.builder(Color.WHITE, 500).withSunroof().modelName("Mustang").createCar();