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.
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));from abc import ABC, abstractmethod
from typing import Callable, Literal
class ReceiptPrinter(ABC):
@abstractmethod
def print(self, lines: list[str]) -> str: ...
class CardReader(ABC):
@abstractmethod
def charge(self, amount_cents: int) -> str: ...
class CashDrawer(ABC):
@abstractmethod
def open(self) -> str: ...
class HardwareKit(ABC):
@abstractmethod
def create_printer(self) -> ReceiptPrinter: ...
@abstractmethod
def create_card_reader(self) -> CardReader: ...
@abstractmethod
def create_cash_drawer(self) -> CashDrawer: ...
def money(cents: int) -> str:
return f"{cents / 100:.2f}"
class KestrelPrinter(ReceiptPrinter):
def print(self, lines: list[str]) -> str:
return "Kestrel serial printer: " + " | ".join(lines)
class KestrelCardReader(CardReader):
def charge(self, amount_cents: int) -> str:
return f"Kestrel reader charged {money(amount_cents)} over serial"
class KestrelCashDrawer(CashDrawer):
def open(self) -> str:
return "Kestrel drawer kicked through printer port"
class OrbixPrinter(ReceiptPrinter):
def print(self, lines: list[str]) -> str:
return "Orbix USB printer: " + " | ".join(lines)
class OrbixCardReader(CardReader):
def charge(self, amount_cents: int) -> str:
return f"Orbix reader charged {money(amount_cents)} over USB"
class OrbixCashDrawer(CashDrawer):
def open(self) -> str:
return "Orbix drawer opened by its USB controller"
class KestrelKit(HardwareKit):
def create_printer(self) -> ReceiptPrinter:
return KestrelPrinter()
def create_card_reader(self) -> CardReader:
return KestrelCardReader()
def create_cash_drawer(self) -> CashDrawer:
return KestrelCashDrawer()
class OrbixKit(HardwareKit):
def create_printer(self) -> ReceiptPrinter:
return OrbixPrinter()
def create_card_reader(self) -> CardReader:
return OrbixCardReader()
def create_cash_drawer(self) -> CashDrawer:
return OrbixCashDrawer()
PaymentMethod = Literal["card", "cash"]
class Checkout:
def __init__(self, kit: HardwareKit) -> None:
self._printer = kit.create_printer()
self._reader = kit.create_card_reader()
self._drawer = kit.create_cash_drawer()
def complete_sale(self, total_cents: int, method: PaymentMethod) -> list[str]:
log: list[str] = []
if method == "card":
log.append(self._reader.charge(total_cents))
else:
log.append(self._drawer.open())
log.append(self._printer.print([f"Total {money(total_cents)}", f"Paid by {method}"]))
return log
KITS: dict[str, Callable[[], HardwareKit]] = {
"kestrel": KestrelKit,
"orbix": OrbixKit,
}
def kit_for(vendor: str) -> HardwareKit:
make = KITS.get(vendor)
if make is None:
raise ValueError(f"Unknown hardware vendor: {vendor}")
return make()
if __name__ == "__main__":
old_store_lane = Checkout(kit_for("kestrel"))
for line in old_store_lane.complete_sale(1250, "card"):
print(line)
new_store_lane = Checkout(kit_for("orbix"))
for line in new_store_lane.complete_sale(830, "cash"):
print(line)<?php
declare(strict_types=1);
interface ReceiptPrinter
{
public function print(array $lines): string;
}
interface CardReader
{
public function charge(int $amountCents): string;
}
interface CashDrawer
{
public function open(): string;
}
interface HardwareKit
{
public function createPrinter(): ReceiptPrinter;
public function createCardReader(): CardReader;
public function createCashDrawer(): CashDrawer;
}
function money(int $cents): string
{
return number_format($cents / 100, 2, '.', '');
}
final class KestrelPrinter implements ReceiptPrinter
{
public function print(array $lines): string
{
return 'Kestrel serial printer: ' . implode(' | ', $lines);
}
}
final class KestrelCardReader implements CardReader
{
public function charge(int $amountCents): string
{
return 'Kestrel reader charged ' . money($amountCents) . ' over serial';
}
}
final class KestrelCashDrawer implements CashDrawer
{
public function open(): string
{
return 'Kestrel drawer kicked through printer port';
}
}
final class OrbixPrinter implements ReceiptPrinter
{
public function print(array $lines): string
{
return 'Orbix USB printer: ' . implode(' | ', $lines);
}
}
final class OrbixCardReader implements CardReader
{
public function charge(int $amountCents): string
{
return 'Orbix reader charged ' . money($amountCents) . ' over USB';
}
}
final class OrbixCashDrawer implements CashDrawer
{
public function open(): string
{
return 'Orbix drawer opened by its USB controller';
}
}
final class KestrelKit implements HardwareKit
{
public function createPrinter(): ReceiptPrinter
{
return new KestrelPrinter();
}
public function createCardReader(): CardReader
{
return new KestrelCardReader();
}
public function createCashDrawer(): CashDrawer
{
return new KestrelCashDrawer();
}
}
final class OrbixKit implements HardwareKit
{
public function createPrinter(): ReceiptPrinter
{
return new OrbixPrinter();
}
public function createCardReader(): CardReader
{
return new OrbixCardReader();
}
public function createCashDrawer(): CashDrawer
{
return new OrbixCashDrawer();
}
}
final class Checkout
{
private readonly ReceiptPrinter $printer;
private readonly CardReader $reader;
private readonly CashDrawer $drawer;
public function __construct(HardwareKit $kit)
{
$this->printer = $kit->createPrinter();
$this->reader = $kit->createCardReader();
$this->drawer = $kit->createCashDrawer();
}
/** @return string[] */
public function completeSale(int $totalCents, string $method): array
{
$log = [];
$log[] = $method === 'card'
? $this->reader->charge($totalCents)
: $this->drawer->open();
$log[] = $this->printer->print(['Total ' . money($totalCents), 'Paid by ' . $method]);
return $log;
}
}
function kitFor(string $vendor): HardwareKit
{
return match ($vendor) {
'kestrel' => new KestrelKit(),
'orbix' => new OrbixKit(),
default => throw new InvalidArgumentException("Unknown hardware vendor: {$vendor}"),
};
}
$oldStoreLane = new Checkout(kitFor('kestrel'));
foreach ($oldStoreLane->completeSale(1250, 'card') as $line) {
echo $line, PHP_EOL;
}
$newStoreLane = new Checkout(kitFor('orbix'));
foreach ($newStoreLane->completeSale(830, 'cash') as $line) {
echo $line, PHP_EOL;
}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 == ...orswitch (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
FakeKitthat 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.
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.
Define an interface for each product kind, containing only the operations client code actually needs.
Write one concrete class per product per variant, each implementing its product interface.
Declare the abstract factory interface with one creation method per product kind, returning the product interfaces.
Implement one concrete factory per variant. Each creation method returns that variant's product and nothing else.
Change client classes to accept a factory (usually through the constructor) and create products only through it.
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.
- Factory Method: Let Subclasses Decide Which Object to Create
Each creation method on an abstract factory is often a factory method. Factory Method creates one product through subclassing; Abstract Factory groups several such methods so a whole family is chosen together.
- Builder Pattern: Assemble Complex Objects Step by Step
Builder assembles one complex object step by step and returns it at the end. Abstract Factory returns finished products immediately, and its focus is on which family they come from.
- Prototype Pattern: Create Objects by Cloning a Configured Instance
A concrete factory can hold prototype instances and clone them instead of calling constructors, which helps when products are expensive to configure.
- Singleton: One Shared Instance, and Why You Usually Want DI Instead
An application usually needs only one instance of each concrete factory, so factories are sometimes made singletons. Passing the factory in explicitly is usually easier to test.
- Bridge Pattern: Split Abstraction from Implementation
When Bridge separates an abstraction from platform-specific implementations, Abstract Factory can create the matching implementation objects and hide the platform choice from the abstraction.
- Repeated Switches: the same type-code switch scattered across a codebase
The same vendor switch scattered across many files is the classic smell that Abstract Factory removes, by replacing all of them with one factory selection.
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.