← 一覧に戻る

Builder

生成パターン

複雑なオブジェクトの構築を段階的に行い、同じ構築プロセスで異なる表現を作成可能にする。

目次
  1. クラス図
  2. シーケンス図
  3. 使いどころ
  4. コード例
  5. AIプロンプト例
  6. 関連パターン

クラス図

シーケンス図

使いどころ

コード例

製品クラス + 内部Builder

public class User {
    private final String id;
    private final String name;
    private final String email;
    private final int age;

    private User(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.email = builder.email;
        this.age = builder.age;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private String id;
        private String name;
        private String email;
        private int age;

        public Builder id(String id) { this.id = id; return this; }
        public Builder name(String name) { this.name = name; return this; }
        public Builder email(String email) { this.email = email; return this; }
        public Builder age(int age) { this.age = age; return this; }

        public User build() {
            if (id == null || name == null) {
                throw new IllegalStateException("id and name are required");
            }
            return new User(this);
        }
    }
}

使用例

// 必須項目のみ
User user1 = User.builder()
    .id("U001")
    .name("田中太郎")
    .build();

// 全項目指定(メソッドチェーン)
User user2 = User.builder()
    .id("U002")
    .name("鈴木花子")
    .email("hanako@example.com")
    .age(28)
    .build();

AIプロンプト例

カスタマイズ用プロンプト

以下のBuilderパターンでクラスを作成してください。

【クラス名】
HttpRequest

【フィールド(必須)】
・url: String
・method: String (GET/POST/PUT/DELETE)

【フィールド(オプション)】
・headers: Map<String, String>
・body: String
・timeout: int (デフォルト30秒)

【バリデーション】
・urlは必須、http/httpsで始まること
← 一覧に戻る