15 minlesson

Factory Patterns Comparison

Factory Patterns Comparison

Understanding when to use Factory Method vs Abstract Factory.

Factory Method

Creates one product type, varies by subclass:

typescript
1abstract class NotificationFactory {
2 abstract createNotification(): Notification;
3
4 send(message: string): void {
5 const notification = this.createNotification();
6 notification.send(message);
7 }
8}
9
10class EmailNotificationFactory extends NotificationFactory {
11 createNotification() { return new EmailNotification(); }
12}
13
14class SMSNotificationFactory extends NotificationFactory {
15 createNotification() { return new SMSNotification(); }
16}

Abstract Factory

Creates families of related products:

typescript
1interface NotificationFactory {
2 createNotification(): Notification;
3 createTemplate(): Template;
4 createDeliveryChannel(): DeliveryChannel;
5}
6
7class 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:

typescript
1abstract class AddressFactory {
2 // Factory methods for each product
3 abstract createFormatter(): AddressFormatter;
4 abstract createValidator(): AddressValidator;
5
6 // Template method using factories
7 createService(): AddressService {
8 return new AddressService(
9 this.createFormatter(),
10 this.createValidator()
11 );
12 }
13}