Skip to content

Abstract Factory: Create Families of Objects That Belong Together

Learn the Abstract Factory pattern through a point-of-sale example, with diagrams, pseudocode, TypeScript, Python and PHP code, and interview questions.

12 min readDesign patternCreational

Provide an interface for creating families of related or dependent objects without naming their concrete classes, so that client code always receives products that are designed to work together.

Abstract Factory is the pattern you reach for when objects only work correctly as a matched set. Instead of creating each object separately and hoping they fit together, client code asks one factory for the whole family. Swapping the factory swaps every product at once, so a mismatched combination can never reach production. This guide follows one invented system from start to finish: a point-of-sale app that drives receipt printers, card readers and cash drawers from two hardware vendors. You will see the problem, the structure, pseudocode, working code in three languages, and the trade-offs interviewers usually ask about.

The problem

A situation where the obvious design starts to hurt.

You work on Tillwise, the point-of-sale software running in 340 grocery stores. Every checkout lane has three devices: a receipt printer, a card reader and a cash drawer. The stores use two hardware kits. Older stores run the Kestrel kit, where everything talks over a serial line and the cash drawer opens by sending a kick signal through the printer port. Newer stores run the Orbix kit, where every device is on USB and the drawer has its own controller.

The checkout code creates each device directly. To pick the right class it checks a vendor setting, and that check now appears 23 times across the codebase: when printing, when charging, when opening the drawer, when running diagnostics. Each device is chosen independently from its own config key.

That independence caused a real incident. A technician copied a config file between stores and 12 lanes ended up with an Orbix card reader next to a Kestrel printer and drawer. Cards were charged, but the code that opened the drawer assumed the Orbix controller, so cash sales hung until a manager opened the drawer with a key.

Next quarter a third vendor, Pellam, arrives. Adding it means touching all 23 branches and hoping nobody forgets one. You need a way to guarantee that a lane always gets a printer, reader and drawer from the same kit, and to add a new kit without editing checkout logic.

The solution

What the pattern proposes.

Abstract Factory splits the problem into two hierarchies. First, define an interface for each kind of product: ReceiptPrinter, CardReader and CashDrawer. Every vendor provides its own classes that implement them, such as KestrelPrinter and OrbixPrinter.

Second, define one factory interface, HardwareKit, with a creation method per product: createPrinter(), createCardReader() and createCashDrawer(). Each vendor gets one concrete factory, KestrelKit or OrbixKit, that returns only its own products. The pairing rules live in exactly one class per vendor.

The Checkout class receives a HardwareKit in its constructor and asks it for all three devices. It only ever talks to the product interfaces, so it has no idea which vendor is behind them. It cannot end up with a mixed set, because the only thing that knows how to build devices is a single kit.

The vendor check shrinks from 23 places to one: the startup code that maps the store's vendor setting to a kit. Supporting Pellam means writing three product classes and one PellamKit, then adding one entry to that map. Checkout, diagnostics and reporting code stay untouched.

An everyday analogy

The same idea, outside software.

Think about cordless power tools. Each brand sells a battery platform: drills, sanders, chargers and batteries that share the same connector and voltage. Once you commit to a brand, you buy everything from that line, and it all fits. You never try to clip one brand's battery into another brand's drill, because the shapes simply do not match.

The brand's product line is the concrete factory. Drill, battery and charger are the abstract products, and each brand's versions are the concrete products. You, the person building a bookshelf, are the client: you just pick up the drill and use it, without caring how the battery talks to the motor. Switching brands means replacing the whole set, not one piece.

Structure

The pieces and how they relate.

Checkout depends only on interfaces; each kit creates a matching printer, reader and drawer.Checkout calls HardwareKit (creates devices via). KestrelKit implements HardwareKit. OrbixKit implements HardwareKit. Checkout calls ReceiptPrinter. Checkout calls CardReader. Checkout calls CashDrawer. KestrelPrinter implements ReceiptPrinter. OrbixPrinter implements ReceiptPrinter. KestrelCardReader implements CardReader. OrbixCardReader implements CardReader. KestrelCashDrawer implements CashDrawer. OrbixCashDrawer implements CashDrawer. KestrelKit creates KestrelPrinter. KestrelKit creates KestrelCardReader. KestrelKit creates KestrelCashDrawer. OrbixKit creates OrbixPrinter. OrbixKit creates OrbixCardReader. OrbixKit creates OrbixCashDrawer.CheckoutcompleteSale(totalCents,method)«interface»HardwareKitcreatePrinter,createCardReader…KestrelKitserial devicesOrbixKitUSB devices«interface»ReceiptPrinterprint(lines)«interface»CardReadercharge(amountCents)«interface»CashDraweropen()KestrelPrinterKestrelCardReaderKestrelCashDrawerOrbixPrinterOrbixCardReaderOrbixCashDrawercreates devices via
Checkout depends only on interfaces; each kit creates a matching printer, reader and drawer.

Participants

Abstract Factory (HardwareKit)
Declares one creation method per product in the family: createPrinter(), createCardReader(), createCashDrawer(). Return types are the product interfaces, never concrete classes.
Concrete Factory (KestrelKit, OrbixKit)
Implements every creation method for one vendor. It is the only place that knows which concrete classes belong together, which is what guarantees a consistent family.
Abstract Product (ReceiptPrinter, CardReader, CashDrawer)
Interfaces for each kind of device. Client code is written entirely against these.
Concrete Product (KestrelPrinter, OrbixCardReader, ...)
Vendor-specific implementations. Products in the same family may rely on each other, such as the Kestrel drawer opening through the Kestrel printer port.
Client (Checkout)
Receives a factory, asks it for products and uses them through their interfaces. It never names a vendor class, so it works unchanged with any kit.

Pseudocode

The solution to the scenario, language-neutral.

interface ReceiptPrinter
    method print(lines): string

interface CardReader
    method charge(amountCents): string

interface CashDrawer
    method open(): string

interface HardwareKit
    method createPrinter(): ReceiptPrinter
    method createCardReader(): CardReader
    method createCashDrawer(): CashDrawer

class KestrelKit implements HardwareKit
    method createPrinter() is return new KestrelPrinter()
    method createCardReader() is return new KestrelCardReader()
    method createCashDrawer() is return new KestrelCashDrawer()

class OrbixKit implements HardwareKit
    method createPrinter() is return new OrbixPrinter()
    method createCardReader() is return new OrbixCardReader()
    method createCashDrawer() is return new OrbixCashDrawer()

class Checkout
    field printer, reader, drawer

    constructor Checkout(kit: HardwareKit)
        printer = kit.createPrinter()
        reader = kit.createCardReader()
        drawer = kit.createCashDrawer()

    method completeSale(totalCents, method)
        log = []
        if method == "card" then log.add(reader.charge(totalCents))
        else log.add(drawer.open())
        log.add(printer.print(["Total " + money(totalCents), "Paid by " + method]))
        return log

// the only place that looks at the vendor setting
function kitFor(vendor)
    if vendor == "kestrel" then return new KestrelKit()
    if vendor == "orbix" then return new OrbixKit()
    throw UnknownVendor(vendor)

lane = new Checkout(kitFor(storeConfig.vendor))
lane.completeSale(1250, "card")

The code

The same solution in TypeScript, Python and PHP.

interface ReceiptPrinter {
  print(lines: string[]): string;
}

interface CardReader {
  charge(amountCents: number): string;
}

interface CashDrawer {
  open(): string;
}

interface HardwareKit {
  createPrinter(): ReceiptPrinter;
  createCardReader(): CardReader;
  createCashDrawer(): CashDrawer;
}

const money = (cents: number): string => (cents / 100).toFixed(2);

class KestrelPrinter implements ReceiptPrinter {
  print(lines: string[]): string {
    return `Kestrel serial printer: ${lines.join(" | ")}`;
  }
}

class KestrelCardReader implements CardReader {
  charge(amountCents: number): string {
    return `Kestrel reader charged ${money(amountCents)} over serial`;
  }
}

class KestrelCashDrawer implements CashDrawer {
  open(): string {
    return "Kestrel drawer kicked through printer port";
  }
}

class OrbixPrinter implements ReceiptPrinter {
  print(lines: string[]): string {
    return `Orbix USB printer: ${lines.join(" | ")}`;
  }
}

class OrbixCardReader implements CardReader {
  charge(amountCents: number): string {
    return `Orbix reader charged ${money(amountCents)} over USB`;
  }
}

class OrbixCashDrawer implements CashDrawer {
  open(): string {
    return "Orbix drawer opened by its USB controller";
  }
}

class KestrelKit implements HardwareKit {
  createPrinter(): ReceiptPrinter {
    return new KestrelPrinter();
  }
  createCardReader(): CardReader {
    return new KestrelCardReader();
  }
  createCashDrawer(): CashDrawer {
    return new KestrelCashDrawer();
  }
}

class OrbixKit implements HardwareKit {
  createPrinter(): ReceiptPrinter {
    return new OrbixPrinter();
  }
  createCardReader(): CardReader {
    return new OrbixCardReader();
  }
  createCashDrawer(): CashDrawer {
    return new OrbixCashDrawer();
  }
}

type PaymentMethod = "card" | "cash";

class Checkout {
  private readonly printer: ReceiptPrinter;
  private readonly reader: CardReader;
  private readonly drawer: CashDrawer;

  constructor(kit: HardwareKit) {
    this.printer = kit.createPrinter();
    this.reader = kit.createCardReader();
    this.drawer = kit.createCashDrawer();
  }

  completeSale(totalCents: number, method: PaymentMethod): string[] {
    const log: string[] = [];
    log.push(method === "card" ? this.reader.charge(totalCents) : this.drawer.open());
    log.push(this.printer.print([`Total ${money(totalCents)}`, `Paid by ${method}`]));
    return log;
  }
}

const kits: Record<string, () => HardwareKit> = {
  kestrel: () => new KestrelKit(),
  orbix: () => new OrbixKit(),
};

function kitFor(vendor: string): HardwareKit {
  const make = kits[vendor];
  if (!make) {
    throw new Error(`Unknown hardware vendor: ${vendor}`);
  }
  return make();
}

const oldStoreLane = new Checkout(kitFor("kestrel"));
oldStoreLane.completeSale(1250, "card").forEach((line) => console.log(line));

const newStoreLane = new Checkout(kitFor("orbix"));
newStoreLane.completeSale(830, "cash").forEach((line) => console.log(line));

When to use it

Situations where it pays off.

  • Your code needs several kinds of objects that must come from the same variant, such as devices from one vendor, clients for one cloud provider, or adapters for one database engine.

    The concrete factory makes the valid combinations explicit. Clients cannot assemble a mixed set by accident, which removes a whole class of configuration bugs like the 12 broken Tillwise lanes.

  • You expect to add whole new variants over time, like the Pellam kit next quarter.

    A new variant is a new factory plus its products. Existing client code does not change, so the risk of a release is limited to the new classes.

  • The same if vendor == ... or switch (provider) check is repeated across many files.

    Each repetition is a place where a new variant can be forgotten. Abstract Factory concentrates that decision into one lookup at startup and uses polymorphism everywhere else.

  • You want to test client code with fake products.

    A test can pass a FakeKit that returns in-memory doubles for all products at once, so checkout logic is tested without real hardware.

How to implement it

Steps to introduce it in existing code.

  1. List the product kinds that form a family (printer, card reader, cash drawer) and the variants that exist (Kestrel, Orbix). A small table of products by variants makes the shape obvious.

  2. Define an interface for each product kind, containing only the operations client code actually needs.

  3. Write one concrete class per product per variant, each implementing its product interface.

  4. Declare the abstract factory interface with one creation method per product kind, returning the product interfaces.

  5. Implement one concrete factory per variant. Each creation method returns that variant's product and nothing else.

  6. Change client classes to accept a factory (usually through the constructor) and create products only through it.

  7. Put the variant decision in one place, typically a lookup at application startup, and delete the scattered vendor checks.

Pros and cons

What you gain and what you pay.

Pros

  • Products created by one factory are guaranteed to be compatible with each other.
  • Client code depends only on interfaces, so it stays free of vendor or platform classes.
  • Adding a new variant does not require changes to client code, which follows the open/closed principle.
  • Creation logic for a variant lives in one class, so it is easy to find and review.
  • Swapping a whole family for tests or demos is a single constructor argument.

Cons

  • Adding a new product kind, such as a barcode scanner, means changing the factory interface and every concrete factory.
  • The number of classes grows as products times variants: three products and three vendors already need nine product classes and three factories.
  • For a single product or a single variant, the extra interfaces are indirection with no payoff.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between Abstract Factory and Factory Method?

Factory Method is a single creation method that subclasses override to decide which one product to build. Abstract Factory is an object with several creation methods, one per product kind, and its purpose is to keep a whole family consistent. In practice the methods inside an abstract factory are often implemented as factory methods. A good one-line answer in an interview: Factory Method varies one product by inheritance, Abstract Factory varies a family of products by composition.

How do you add a new product kind without breaking every factory?

You cannot avoid touching every factory, because the interface itself changes. You can soften it: add the new method with a default implementation that throws or returns a null object, then fill in each vendor. Be honest in an interview that this is the pattern's main weakness. It makes new variants cheap and new product kinds expensive.

Where should the code that chooses the concrete factory live?

In one place near application startup or in your dependency injection configuration, such as the kitFor function reading the store's vendor setting. After that, the factory is passed into the classes that need it. If you find vendor checks creeping back into business code, the selection has leaked.

Do I need a class hierarchy for this in Python or TypeScript?

Not strictly. In languages with first-class functions, a factory can be a plain object or dictionary of creation functions with a typed shape. The essential idea is unchanged: one value groups the creators for a family, and the client only sees the product interfaces. Classes simply make the contract and the type checking more explicit.

When is Abstract Factory overkill?

When there is only one variant and no realistic second one, or when products do not depend on each other at all. In those cases plain constructors or a single factory function are clearer. The pattern earns its keep when mixing variants would be a real bug and new variants are expected.

Next guide3 of 5 · Creational patternsBuilder Pattern: Assemble Complex Objects Step by StepRead the next one