生成パターン
オブジェクト生成をサブクラスに委譲し、生成するクラスを柔軟に切り替える。new演算子の直接使用を避ける。
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", "処理が完了しました");
以下のFactory Methodパターンをカスタマイズしてください。 【要件】 ・用途: [例: ドキュメント生成] ・製品の種類: [例: PDF/Excel/CSV/HTML] ・共通インターフェース名: [例: DocumentGenerator] 【共通メソッド】 ・generate(Data data): byte[] - ドキュメント生成 ・getContentType(): String - MIMEタイプ ・getExtension(): String - ファイル拡張子