Factory Patterns Comparison
Understanding when to use Factory Method vs Abstract Factory.
Factory Method
Creates one product type, varies by subclass:
typescript1abstract class NotificationFactory {2 abstract createNotification(): Notification;34 send(message: string): void {5 const notification = this.createNotification();6 notification.send(message);7 }8}910class EmailNotificationFactory extends NotificationFactory {11 createNotification() { return new EmailNotification(); }12}1314class SMSNotificationFactory extends NotificationFactory {15 createNotification() { return new SMSNotification(); }16}
Abstract Factory
Creates families of related products:
typescript1interface NotificationFactory {2 createNotification(): Notification;3 createTemplate(): Template;4 createDeliveryChannel(): DeliveryChannel;5}67class EmailNotificationFactory implements NotificationFactory {8 createNotification() { return new EmailNotification(); }9 createTemplate() { return new EmailTemplate(); }10 createDeliveryChannel() { return new SMTPChannel(); }11}
Decision Guide
Use Factory Method when:
- You have one product type to create
- Subclasses should control instantiation
- You want to provide extension points
Use Abstract Factory when:
- You have families of related products
- Products must be used together
- You need to ensure consistency
Combining Both
Abstract Factory often uses Factory Method internally:
typescript1abstract class AddressFactory {2 // Factory methods for each product3 abstract createFormatter(): AddressFormatter;4 abstract createValidator(): AddressValidator;56 // Template method using factories7 createService(): AddressService {8 return new AddressService(9 this.createFormatter(),10 this.createValidator()11 );12 }13}