Factory Method
生成パターン
オブジェクト生成をサブクラスに委譲し、生成するクラスを柔軟に切り替える。new演算子の直接使用を避ける。
クラス図
シーケンス図
使いどころ
- 通知送信(メール/SMS/Push/Slack)
- ドキュメント生成(PDF/Excel/Word)
- データベース接続(MySQL/PostgreSQL/Oracle)
- ログ出力先の切り替え
- テスト用モックオブジェクトの生成
コード例
製品インターフェース
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 - ファイル拡張子