When to Use It
- When an object has many optional fields or configurations.
- When object construction involves complex steps or validation.
- When you want to avoid constructor telescoping (i.e., multiple constructors with different parameters).
定义
建造者模式(Builder Pattern)将一个复杂对象的构建与它的表示分离,使得同样的构建过程(但传入的参数不同)可以创建不同的表示。
构成
The Builder pattern typically involves:
- Product – the complex object being built.
- Builder – an interface or abstract class defining building steps.
- ConcreteBuilder – implements the Builder, maintaining the product.
- Director (optional) – controls the building sequence.
Java Example
public class House {
private int rooms;
private int floors;
private boolean hasGarage;
private boolean hasSwimmingPool;
private House(Builder builder) {
this.rooms = builder.rooms;
this.floors = builder.floors;
this.hasGarage = builder.hasGarage;
this.hasSwimmingPool = builder.hasSwimmingPool;
}
public static class Builder {
private int rooms;
private int floors;
private boolean hasGarage;
private boolean hasSwimmingPool;
public Builder rooms(int rooms) {
this.rooms = rooms;
return this;
}
public Builder floors(int floors) {
this.floors = floors;
return this;
}
public Builder hasGarage(boolean hasGarage) {
this.hasGarage = hasGarage;
return this;
}
public Builder hasSwimmingPool(boolean hasSwimmingPool) {
this.hasSwimmingPool = hasSwimmingPool;
return this;
}
public House build() {
return new House(this);
}
}
}
// usage
House myHouse = new House.Builder()
.rooms(4)
.floors(2)
.hasGarage(true)
.hasSwimmingPool(false)
.build();
Pros and Cons
✅ Pros
...