7
Back to Boss Battles

Factory MethodVSAbstract Factory

The Problem

Scenario A β€” Factory Method territory: You are building a notification service. Each notification channel (email, SMS, push) has a different sender object. Each channel module overrides a createSender() method to produce the right sender. There is one product type: a sender.

Scenario B β€” Abstract Factory territory: You are building a multi-tenant payment system. Each region (India, US, EU) needs a family of related objects: a payment gateway, a tax calculator, and an invoice formatter β€” all consistent for that region. You cannot mix a US gateway with an Indian tax calculator.


Why They Look Alike

Both create objects without specifying their concrete classes. Both use polymorphism to defer instantiation. The word "factory" appears in both names, and beginners often hear "factory pattern" and cannot tell which one is meant.

Rendering diagram…

The diagram above is Factory Method β€” one product hierarchy, one creator hierarchy.

Rendering diagram…

Abstract Factory β€” one factory produces a family of related products.


The Fundamental Difference

Factory Method creates one product via subclass override. Abstract Factory creates a family of related products via a factory object.


Decision Rule

CluePattern
"One object needs to be created, and the type varies"Factory Method
"Multiple related objects must be created together consistently"Abstract Factory
"Subclasses decide which class to instantiate"Factory Method
"Swap an entire family of objects by switching the factory"Abstract Factory
"Single method returning one polymorphic product"Factory Method
"Object with multiple create methods returning related products"Abstract Factory

Side-by-Side Code

Factory Method β€” one product

typescript
1// One product: NotificationSender
2interface NotificationSender {
3 send(to: string, message: string): void;
4}
5
6class EmailSender implements NotificationSender {
7 send(to: string, message: string) {
8 console.log(`Email to ${to}: ${message}`);
9 }
10}
11
12class SmsSender implements NotificationSender {
13 send(to: string, message: string) {
14 console.log(`SMS to ${to}: ${message}`);
15 }
16}
17
18// Creator with a factory method
19abstract class NotificationChannel {
20 abstract createSender(): NotificationSender;
21
22 notify(to: string, message: string) {
23 const sender = this.createSender();
24 sender.send(to, message);
25 }
26}
27
28class EmailChannel extends NotificationChannel {
29 createSender() { return new EmailSender(); }
30}
31
32class SmsChannel extends NotificationChannel {
33 createSender() { return new SmsSender(); }
34}

Abstract Factory β€” family of products

typescript
1// Family: gateway + tax calculator + invoice formatter
2interface PaymentGateway {
3 charge(amount: number): string;
4}
5interface TaxCalculator {
6 calculate(amount: number): number;
7}
8interface InvoiceFormatter {
9 format(data: Record<string, unknown>): string;
10}
11
12// Abstract factory
13interface RegionalFactory {
14 createGateway(): PaymentGateway;
15 createTaxCalculator(): TaxCalculator;
16 createInvoiceFormatter(): InvoiceFormatter;
17}
18
19// India family
20class RazorpayGateway implements PaymentGateway {
21 charge(amount: number) { return `Razorpay charged β‚Ή${amount}`; }
22}
23class GSTCalculator implements TaxCalculator {
24 calculate(amount: number) { return amount * 0.18; }
25}
26class IndianInvoice implements InvoiceFormatter {
27 format(data: Record<string, unknown>) { return `GST Invoice: ${JSON.stringify(data)}`; }
28}
29
30class IndiaFactory implements RegionalFactory {
31 createGateway() { return new RazorpayGateway(); }
32 createTaxCalculator() { return new GSTCalculator(); }
33 createInvoiceFormatter() { return new IndianInvoice(); }
34}
35
36// US family
37class StripeGateway implements PaymentGateway {
38 charge(amount: number) { return `Stripe charged $${amount}`; }
39}
40class SalesTaxCalculator implements TaxCalculator {
41 calculate(amount: number) { return amount * 0.08; }
42}
43class USInvoice implements InvoiceFormatter {
44 format(data: Record<string, unknown>) { return `US Invoice: ${JSON.stringify(data)}`; }
45}
46
47class USFactory implements RegionalFactory {
48 createGateway() { return new StripeGateway(); }
49 createTaxCalculator() { return new SalesTaxCalculator(); }
50 createInvoiceFormatter() { return new USInvoice(); }
51}
52
53// Client uses the factory β€” all products are consistent
54function processOrder(factory: RegionalFactory, amount: number) {
55 const gw = factory.createGateway();
56 const tax = factory.createTaxCalculator();
57 const fmt = factory.createInvoiceFormatter();
58
59 const taxAmount = tax.calculate(amount);
60 const result = gw.charge(amount + taxAmount);
61 console.log(fmt.format({ result, tax: taxAmount }));
62}

Key difference: Factory Method = one createX() method overridden by subclasses. Abstract Factory = one object with multiple createX() methods producing a consistent family.


Scenario Quiz

?Knowledge Check

1A logging system needs to create a logger (file, console, or cloud). Each logger type is created by overriding a method in a base LogService. Which pattern?

2A UI theming system creates buttons, inputs, and modals that must all match the same theme (dark or light). Mixing a dark button with a light modal would look broken. Which pattern?

3A report generator creates a DataFetcher. Subclasses SqlReportGenerator and ApiReportGenerator create different fetchers. Which pattern?

4A multi-database ORM needs to create Connection, QueryBuilder, and MigrationRunner objects that are all compatible with the same database engine (Postgres vs MySQL). Which pattern?

5A message queue adapter creates a Producer object. KafkaQueueAdapter and RabbitMQQueueAdapter override the creation. Which pattern?

6A cloud provider abstraction creates compute instances, storage buckets, and DNS records β€” all from the same provider (AWS vs GCP vs Azure). Which pattern?

7An auth system creates a TokenValidator. JWTAuth overrides it to create JWTValidator, SessionAuth creates SessionValidator. Which pattern?

8You need to create just one type of object (a cache client) based on a config string ('redis' or 'memcached'). No families, no subclasses. Which pattern?