當類構造函數參數超過 4 個、或存在大量可選參數時,建造者模式是構建複雜對象的標準解法,解決重疊構造器、參數順序易錯、不可變對象構建難等問題。
User)。
public final class User {
private final String userId; // 必填
private final String username; // 必填
private final String email; // 可選
private final String phone; // 可選
private final int age; // 可選
private final Set<String> roles; // 可選
private User(Builder builder) {
this.userId = builder.userId;
this.username = builder.username;
this.email = builder.email;
this.phone = builder.phone;
this.age = builder.age;
this.roles = builder.roles;
}
public static class Builder {
// 必填參數
private final String userId;
private final String username;
// 可選參數(默認值)
private String email = "";
private String phone = "";
private int age = 0;
private Set<String> roles = Collections.emptySet();
public Builder(String userId, String username) {
this.userId = userId;
this.username = username;
}
public Builder email(String val) { this.email = val; return this; }
public Builder phone(String val) { this.phone = val; return this; }
public Builder age(int val) { this.age = val; return this; }
public Builder roles(Set<String> val) { this.roles = val; return this; }
public User build() {
// 可在此驗證業務規則
if (age < 0) throw new IllegalStateException("年齡不能為負");
return new User(this);
}
}
}
// 使用:一行代碼構建,參數清晰可讀
User user = new User.Builder("1001", "zhangsan")
.email("zhang@example.com")
.age(25)
.roles(Set.of("ADMIN", "USER"))
.build();
| 變體 | 適用場景 |
|---|---|
Lombok @Builder | 減少樣板代碼,但難以加入驗證邏輯、默認值控制受限 |
| 分階段建造器 | 強制調用順序(如:必填 → 可選 → 構建),利用接口鏈實現編譯期約束 |
| Director + 多 Builder | 構建邏輯復用(如:構建「管理員用戶」「訪客用戶」預設配置) |