Factory Method
TypeScriptApplicationFactory Method in TypeScript
Lets notification creators select the concrete notification channel while the shared delivery workflow depends only on a common notification interface.
TypeScript
interface Notification {
send(recipient: string, message: string): Promise<void>;
}
class EmailNotification implements Notification {
async send(recipient: string, message: string) {
console.log(`Email to ${recipient}: ${message}`);
}
}
class SmsNotification implements Notification {
async send(recipient: string, message: string) {
console.log(`SMS to ${recipient}: ${message}`);
}
}
abstract class NotificationCreator {
async notify(recipient: string, message: string) {
const notification = this.createNotification();
await notification.send(recipient, message);
}
protected abstract createNotification(): Notification;
}
class EmailNotificationCreator extends NotificationCreator {
protected createNotification(): Notification {
return new EmailNotification();
}
}
class SmsNotificationCreator extends NotificationCreator {
protected createNotification(): Notification {
return new SmsNotification();
}
}
const creator = new EmailNotificationCreator();
void creator.notify(
"team@example.com",
"Deployment completed.",
);