首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 設計模式精講:建造者模式從入門到最佳實踐

     編輯:Java 相關知識

當類構造函數參數超過 4 個、或存在大量可選參數時,建造者模式是構建複雜對象的標準解法,解決重疊構造器、參數順序易錯、不可變對象構建難等問題。

核心結構

  • Product:目標對象(如 User)。
  • Builder:定義構建步驟接口。
  • ConcreteBuilder:實現構建邏輯,持有 Product 實例。
  • Director(可選):封裝構建順序,構建特定配置。

經典實現:不可變對象 + 鏈式調用


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();

進階變體

最佳實踐清單

  1. Product 類 final、字段 final、無 setter,保證不可變性。
  2. Builder 內部類 static,避免持有外部類引用。
  3. 必填參數放入 Builder 構造器,可選參數通過 setter 鏈式設置。
  4. build() 方法集中驗證約束(非空、範圍、業務規則)。
  5. 考慮線程安全:Builder 非線程安全,請勿共享實例。

建造者模式不僅優化構建體驗,更是領域驅動設計 (DDD) 中值對象、實體構建的基石。善用它,告別「望參數興嘆」的構造器地獄。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
變體適用場景
Lombok @Builder減少樣板代碼,但難以加入驗證邏輯、默認值控制受限
分階段建造器強制調用順序(如:必填 → 可選 → 構建),利用接口鏈實現編譯期約束
Director + 多 Builder構建邏輯復用(如:構建「管理員用戶」「訪客用戶」預設配置)