建造者模式典型应用场景
目录
建造者模式典型应用场景
建造者模式(Builder Pattern)是一种创建型设计模式,主要用于处理复杂对象的构建过程,尤其是当对象的创建需要多个步骤、参数较多或者构建过程需要灵活控制时。它通过将对象的构建过程与表示分离,允许用户逐步构建对象,同时隐藏内部构建细节。
- 当一个对象需要通过多个步骤才能完成构建,并且每一步的顺序或参数可能不同时。假设你正在开发一个游戏,玩家可以自定义角色(比如战士、法师),角色有多个属性:武器、盔甲、技能、属性点等。如果直接用构造函数创建角色对象,可能需要一个非常复杂的构造函数。如果用默认的构造函数。参数太多太长,可读性差,容易出错。
Character character = new Character("Warrior", "Sword", "Plate Armor", 100, 50, 20, true, false, ...);
应用建造者模式。如下。
Character character = new Character.Builder()
.setType("Warrior")
.setWeapon("Sword")
.setArmor("Plate Armor")
.setHealth(100)
.setMana(50)
.build();
- 允许逐步构建对象。
- 参数可选,调用者可以只设置必要的部分。
- 代码更具可读性,减少构造函数参数爆炸。
- 当一个对象需要通
- 需要创建多种不同配置的对象。假设你在开发一个披萨订购系统,披萨有多种类型(经典、意式、芝心),每种披萨可以选择不同的配料(如奶酪、香肠、橄榄)。如果用传统方式,可能需要写很多构造函数或工厂方法。需要为每个配置单独写一个构造函数。
Pizza classicPizza = new Pizza("Classic", "Cheese", "Tomato", null, null);
Pizza italianPizza = new Pizza("Italian", "Mozzarella", "Basil", "Olive Oil", null);
应用建造者模式
Pizza pizza = new Pizza.Builder()
.setStyle("Italian")
.addTopping("Mozzarella")
.addTopping("Basil")
.addSauce("Olive Oil")
.build();
- 同一个建造者可以创建不同风格的对象。
- 避免为每种配置写独立的构造函数或子类。
3. 不可变对象的构建。在 Java 中,许多类(如 StringBuilder 或某些配置对象)在构建时需要设置多个属性,但对象一旦创建就不允许修改。建造者模式非常适合这种场景。
比如一个不可变的 House 类。
public class House {
private final int floors;
private final String color;
private final boolean hasGarage;
private House(Builder builder) {
this.floors = builder.floors;
this.color = builder.color;
this.hasGarage = builder.hasGarage;
}
public static class Builder {
private int floors;
private String color;
private boolean hasGarage;
public Builder setFloors(int floors) {
this.floors = floors;
return this;
}
public Builder setColor(String color) {
this.color = color;
return this;
}
public Builder setHasGarage(boolean hasGarage) {
this.hasGarage = hasGarage;
return this;
}
public House build() {
return new House(this);
}
}
}
House house = new House.Builder()
.setFloors(2)
.setColor("White")
.setHasGarage(true)
.build();
- 保证对象不可变(通过 final 关键字)。
- 构建过程灵活,调用者可以选择性地设置属性。
4.需要控制构建过程,或者一些属性需要经过校验,合法才能进行初始化。
public class Report {
private String title;
private String content;
private String header;
private Report(Builder builder) {
this.title = builder.title;
this.content = builder.content;
this.header = builder.header;
}
public static class Builder {
private String title;
private String content;
private String header;
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setContent(String content) {
this.content = content;
return this;
}
public Builder setHeader(String header) {
this.header = header;
return this;
}
public Report build() {
if (title == null || title.isEmpty()) {
throw new IllegalStateException("Title cannot be empty");
}
return new Report(this);
}
}
}
- 可以在 build() 方法中添加校验逻辑。
- 构建过程更安全,避免创建不合法的对象。