← 一覧に戻る

Factory Method

生成パターン

オブジェクト生成をサブクラスに委譲し、生成するクラスを柔軟に切り替える。new演算子の直接使用を避ける。

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

クラス図

シーケンス図

使いどころ

コード例

製品インターフェース

public interface Notification {
    void send(String to, String message);
    String getType();
}

具体的な製品

public class EmailNotification implements Notification {
    @Override
    public void send(String to, String message) {
        System.out.println("メール送信: " + to + " - " + message);
    }

    @Override
    public String getType() {
        return "Email";
    }
}

public class SlackNotification implements Notification {
    @Override
    public void send(String to, String message) {
        System.out.println("Slack送信: #" + to + " - " + message);
    }

    @Override
    public String getType() {
        return "Slack";
    }
}

ファクトリ

public class NotificationFactory {
    
    public static Notification create(String type) {
        switch (type.toLowerCase()) {
            case "email":
                return new EmailNotification();
            case "slack":
                return new SlackNotification();
            case "sms":
                return new SmsNotification();
            default:
                throw new IllegalArgumentException(
                    "Unknown notification type: " + type
                );
        }
    }
}

使用例

// 設定から通知タイプを取得
String notificationType = config.get("notification.type");

// ファクトリで生成
Notification notification = NotificationFactory.create(notificationType);
notification.send("user@example.com", "処理が完了しました");

AIプロンプト例

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

以下のFactory Methodパターンをカスタマイズしてください。

【要件】
・用途: [例: ドキュメント生成]
・製品の種類: [例: PDF/Excel/CSV/HTML]
・共通インターフェース名: [例: DocumentGenerator]

【共通メソッド】
・generate(Data data): byte[] - ドキュメント生成
・getContentType(): String - MIMEタイプ
・getExtension(): String - ファイル拡張子
← 一覧に戻る