Abstract Factory Pattern

An Abstract Factory is one object that creates a whole set of related products, and its only job is to guarantee they all belong to the same family. Factory Method answers “which one of these do I build?” – one product, chosen by the subclass you are running in. Abstract Factory answers a different question: “which set do I build?” – several products, chosen by which factory object you hold. The constraint it encodes is these must match, and no number of separate factory methods can state that.

💡 Family = products that are only correct when used together. India’s GST calculator, rupee formatter and PAN/GSTIN validator are one family; the EU’s VAT calculator, euro formatter and VAT-ID validator are another. Mixing members across families is the bug this pattern prevents.

Why this matters: interviewers reach for this whenever a problem has a variant axis – region, platform, tenant, database vendor – and most candidates answer “I’d use a factory”, write one creation method per product, and leave the call site to assemble a consistent set. The follow-up is always “what stops me pairing the Indian tax calculator with the euro formatter?”, and the only answer that scores is one where that pairing does not compile. What gets graded next is the price: adding a product breaks every factory you own.


Prerequisites

  • Factory Pattern – Simple Factory and Factory Method are assumed here, not repeated. That lesson sketches Abstract Factory in half a page with a database-driver family; this is the full treatment
  • Dependency Injection – the factory has to arrive from somewhere, and who passes it in is most of the design
  • Inheritance vs Composition – Factory Method varies behaviour by subclass, Abstract Factory by the object you hold

The Problem: the invoice that charges GST in euros

A payments module serves several regions, and each needs three collaborators that have to agree: a tax calculator, a currency formatter and a compliance validator. Built with a factory method per product, the answer most candidates give:

// One factory method per product, each correct in isolation. India: GST,
// lakh-grouped rupees, PAN and GSTIN. EU: VAT, "1.180,00 EUR", VAT-ID.
public class PaymentComponentFactory {

    public static TaxCalculator createTaxCalculator(Region r) {
        return r == Region.INDIA ? new GstCalculator() : new VatCalculator();
    }
    public static CurrencyFormatter createFormatter(Region r) {
        return r == Region.INDIA ? new RupeeFormatter() : new EuroFormatter();
    }
    public static ComplianceValidator createValidator(Region r) {
        return r == Region.INDIA ? new PanGstinValidator() : new VatIdValidator();
    }
}

// The call site assembles the set, and nothing anywhere checks the assembly.
public class InvoiceService {

    public Invoice issue(Order order, Region region) {
        TaxCalculator tax = PaymentComponentFactory.createTaxCalculator(Region.INDIA); // hotfix
        CurrencyFormatter fmt = PaymentComponentFactory.createFormatter(region);
        ComplianceValidator compliance = PaymentComponentFactory.createValidator(region);

        compliance.validate(order.getBuyerTaxId());
        Money total = tax.applyTo(order.getSubtotal());
        return new Invoice(order.getId(), total, fmt.format(total), tax.breakdown());
    }
}

// Called with region = EU. Compiles. Runs. Passes every unit test that stubs
// one product at a time. Emits "18% GST" above an amount reading "1.180,00 EUR",
// validated against an EU VAT ID.

💡 A currency-carrying Money catches part of this at runtime, but nothing stops a GST rate being applied to a euro order, because a rate is just a number. Learn more →

Three costs, and interviewers press on each:

  1. Nothing in the type system says the three belong together. The product interfaces are unrelated, so every pairing type-checks. Two regions across three products give eight assemblies and exactly two are correct; the other six compile, run, and emit a document a tax authority rejects, with no crash to find in a log.
  2. The correct combination is tribal knowledge, copied by hand. The refund path, the statement renderer and the CSV export each repeat these three calls and each must thread one region through all of them. “All three take the same region” lives in a comment at best, and the fourth caller is where it stops being true.
  3. Adding a region is an audit, not an addition. A third region means editing three methods, then trawling every call site for a hardcoded region or a defaulted fallback. Nothing fails to compile to point at the places to fix, which is backwards: adding a variant should be adding a class.

Class Diagram

classDiagram
    class RegionalPaymentFactory {
        <<interface>>
        +createTaxCalculator() TaxCalculator
        +createCurrencyFormatter() CurrencyFormatter
        +createComplianceValidator() ComplianceValidator
    }
    class IndiaPaymentFactory {
        -GstRateTable rates
    }
    class EuPaymentFactory {
        -VatRateTable rates
        -VatIdLookup vies
    }
    class TaxCalculator {
        <<interface>>
        +applyTo(Money subtotal) TaxedAmount
    }
    class CurrencyFormatter {
        <<interface>>
        +format(Money amount) String
    }
    class ComplianceValidator {
        <<interface>>
        +validate(String taxId)
    }
    class PaymentFactoryRegistry {
        -Map~Region, RegionalPaymentFactory~ byRegion
        +forRegion(Region r) RegionalPaymentFactory
    }
    class InvoiceService {
        +issue(Order order) Invoice
    }

    RegionalPaymentFactory <|.. IndiaPaymentFactory
    RegionalPaymentFactory <|.. EuPaymentFactory
    RegionalPaymentFactory ..> TaxCalculator
    RegionalPaymentFactory ..> CurrencyFormatter
    RegionalPaymentFactory ..> ComplianceValidator
    PaymentFactoryRegistry --> RegionalPaymentFactory
    InvoiceService --> RegionalPaymentFactory

The non-obvious part is what is missing: no relation connects the three product interfaces. The family is not in the product types at all – it lives inside each concrete factory, so exactly one file per region can get the grouping wrong, and that file reads as a checkable list.


Real-World Example: Regional Payments for India and the EU

import java.util.*;   // EnumMap, Map

public enum Region { INDIA, EU }

// ---- Three products, one method each: TaxCalculator.applyTo(Money),
// CurrencyFormatter.format(Money), ComplianceValidator.validate(taxId). No
// product interface knows the other two exist. ----

// ---- The abstract factory: one method per member of the family ----
public interface RegionalPaymentFactory {
    TaxCalculator createTaxCalculator();
    CurrencyFormatter createCurrencyFormatter();
    ComplianceValidator createComplianceValidator();
}

// ---- Family 1: India ----
public final class IndiaPaymentFactory implements RegionalPaymentFactory {
    private final GstRateTable rates;                   // loaded once at startup

    public IndiaPaymentFactory(GstRateTable rates) { this.rates = rates; }

    @Override public TaxCalculator createTaxCalculator() {
        return new GstCalculator(rates);                // CGST and SGST split, by HSN code
    }
    @Override public CurrencyFormatter createCurrencyFormatter() { return new RupeeFormatter(); }
    @Override public ComplianceValidator createComplianceValidator() {
        return new PanGstinValidator();                 // GSTIN checksum, state-code prefix
    }
}

// ---- Family 2: the EU. The different constructor arguments are the point --
// a factory absorbs per-family setup no call site should have to know. ----
public final class EuPaymentFactory implements RegionalPaymentFactory {
    private final VatRateTable rates;
    private final VatIdLookup vies;                     // remote VIES client

    public EuPaymentFactory(VatRateTable rates, VatIdLookup vies) {
        this.rates = rates; this.vies = vies;
    }

    @Override public TaxCalculator createTaxCalculator() { return new VatCalculator(rates); }
    @Override public CurrencyFormatter createCurrencyFormatter() { return new EuroFormatter(); }
    @Override public ComplianceValidator createComplianceValidator() { return new VatIdValidator(vies); }
}

// ---- The consumer takes the FACTORY, never the three products. No
// constructor accepts them separately, and that omission is the design. ----
public final class InvoiceService {
    private final TaxCalculator tax;
    private final CurrencyFormatter formatter;
    private final ComplianceValidator compliance;

    public InvoiceService(RegionalPaymentFactory factory) {
        this.tax = factory.createTaxCalculator();
        this.formatter = factory.createCurrencyFormatter();
        this.compliance = factory.createComplianceValidator();
    }

    public Invoice issue(Order order) throws ComplianceException {
        compliance.validate(order.buyerTaxId());
        TaxedAmount taxed = tax.applyTo(order.subtotal());
        return new Invoice(order.id(), taxed, formatter.format(taxed.total()));
    }
}

// ---- Where the factory comes from: one lookup, built at startup ----
public final class PaymentFactoryRegistry {
    private final Map<Region, RegionalPaymentFactory> byRegion;

    public PaymentFactoryRegistry(GstRateTable gst, VatRateTable vat, VatIdLookup vies) {
        Map<Region, RegionalPaymentFactory> m = new EnumMap<>(Region.class);
        m.put(Region.INDIA, new IndiaPaymentFactory(gst));
        m.put(Region.EU, new EuPaymentFactory(vat, vies));
        this.byRegion = Map.copyOf(m);                  // immutable once the process is up
    }

    public RegionalPaymentFactory forRegion(Region region) {
        RegionalPaymentFactory f = byRegion.get(region);
        if (f == null) throw new UnsupportedRegionException(region);   // never default
        return f;
    }
}

// ---- Usage: resolve the family once, then pass the factory down ----
RegionalPaymentFactory factory = registry.forRegion(order.region());
Invoice invoice = new InvoiceService(factory).issue(order);

// The mismatch is unrepresentable now, not merely discouraged:
//   new InvoiceService(new GstCalculator(gst), new EuroFormatter(), euValidator)
//        -> does not compile, there is no such constructor
from collections.abc import Callable
from dataclasses import dataclass
from functools import partial
from typing import Protocol

# TaxCalculator, CurrencyFormatter and ComplianceValidator are Protocols with
# one method each, exactly as in the Java tab.

class RegionalPaymentFactory(Protocol):
    """Structural typing: any object with these three methods IS a factory."""
    def tax_calculator(self) -> TaxCalculator: ...
    def currency_formatter(self) -> CurrencyFormatter: ...
    def compliance_validator(self) -> ComplianceValidator: ...

# Python spells the family as a frozen bundle of callables more often than as a
# class hierarchy: each field is a zero-arg factory, a class or a bound partial.
@dataclass(frozen=True, slots=True)
class PaymentFamily:
    tax_calculator: Callable[[], TaxCalculator]
    currency_formatter: Callable[[], CurrencyFormatter]
    compliance_validator: Callable[[], ComplianceValidator]

INDIA = PaymentFamily(partial(GstCalculator, rates=GST_RATES),
                      RupeeFormatter, PanGstinValidator)
EU = PaymentFamily(partial(VatCalculator, rates=VAT_RATES), EuroFormatter,
                   partial(VatIdValidator, lookup=VIES_CLIENT))

FAMILIES: dict[str, PaymentFamily] = {"IN": INDIA, "EU": EU}   # the registry

def issue_invoice(order: "Order") -> "Invoice":
    """Consumers take the family, never the three products, so a mixed set has
    no way to arrive here."""
    family = FAMILIES.get(order.region)        # resolved once, at the edge
    if family is None:
        raise UnsupportedRegionError(order.region)

    family.compliance_validator().validate(order.buyer_tax_id)
    taxed = family.tax_calculator().apply_to(order.subtotal)
    return Invoice(order.id, taxed, family.currency_formatter().format(taxed.total))

# A module is a legitimate factory here too: india_payments.py exposing
# tax_calculator, currency_formatter and compliance_validator as module-level
# functions satisfies the Protocol structurally, and importlib.import_module
# becomes the registry.
#include <memory>
#include <stdexcept>
#include <unordered_map>

enum class Region { India, Eu };

// The three products are pure-virtual interfaces as in the Java tab.

class RegionalPaymentFactory {
public:
    virtual ~RegionalPaymentFactory() = default;
    // unique_ptr: each caller owns its products, and the return type is the
    // interface, so no concrete class appears in a signature.
    virtual std::unique_ptr<TaxCalculator> createTaxCalculator() const = 0;
    virtual std::unique_ptr<CurrencyFormatter> createCurrencyFormatter() const = 0;
    virtual std::unique_ptr<ComplianceValidator> createComplianceValidator() const = 0;
};

class IndiaPaymentFactory final : public RegionalPaymentFactory {
    const GstRateTable& rates_;   // owned at startup, outlives every product
public:
    explicit IndiaPaymentFactory(const GstRateTable& rates) : rates_(rates) {}

    std::unique_ptr<TaxCalculator> createTaxCalculator() const override
        { return std::make_unique<GstCalculator>(rates_); }
    std::unique_ptr<CurrencyFormatter> createCurrencyFormatter() const override
        { return std::make_unique<RupeeFormatter>(); }
    std::unique_ptr<ComplianceValidator> createComplianceValidator() const override
        { return std::make_unique<PanGstinValidator>(); }
};
// EuPaymentFactory is the mirror image: VatCalculator, EuroFormatter and
// VatIdValidator, plus the VatIdLookup& it was constructed with.

// A consumer takes the factory by const reference and stores the three
// unique_ptr products it builds, as InvoiceService does in the Java tab.

// The registry owns one factory per region for the life of the process.
class PaymentFactoryRegistry {
    std::unordered_map<Region, std::unique_ptr<RegionalPaymentFactory>> byRegion_;
public:
    void add(Region r, std::unique_ptr<RegionalPaymentFactory> f) { byRegion_[r] = std::move(f); }

    const RegionalPaymentFactory& forRegion(Region r) const {
        auto it = byRegion_.find(r);
        if (it == byRegion_.end()) throw std::out_of_range("unsupported region");
        return *it->second;   // a reference: the factory is never copied or moved
    }
};

Note the ownership asymmetry in the C++ tab. Products come back as unique_ptr, so each consumer owns its own, while the factory is built once at startup and handed out as a const RegionalPaymentFactory& – a reference is right whenever the borrower provably dies first. Use shared_ptr<RegionalPaymentFactory> only when a consumer stores the factory to build products later, such as work queued to a pool that may outlive the handler.


The pattern enforces a constraint the type system cannot otherwise state

Abstract Factory exists to make an invalid combination impossible to construct. Everything else people claim for it – hiding concrete classes, centralising creation, allowing new variants – a plain Simple Factory already gives you. So the test is one question: can you name two products that must not be mixed, and say what breaks when they are? A shrug means you want Factory Method or a Map<Key, Supplier<T>> per product instead.

New families are cheap, new products are expensive

Adding a family costs one class and one registry line, and nothing existing changes – the direction the pattern is built for. Adding a product is a breaking change to every implementation: put createRoundingPolicy() on RegionalPaymentFactory and the build goes red in every concrete factory at once, two today and twenty when you have twenty regions. That asymmetry is the decision rule:

  • Choose Abstract Factory when families change often and the product set is stable: regions, platforms, database dialects, cloud providers.
  • Avoid it while you are still discovering what products the family needs, because an interface you edit every sprint breaks everyone every sprint.

Three ways to get the same guarantee with less ceremony

  • An enum or sealed interface carrying the bundle. When families are closed at compile time, make each one an enum constant returning its three products. switch becomes exhaustive, so the compiler names every site to update when a family appears; you give up plugin extension and per-family constructor arguments.
  • A configuration record validated once at startup. When members are chosen by data – rate tables, per-tenant settings, flags – build one RegionSettings at boot and validate the cross-field rules there. Weaker than a compile-time guarantee, but it catches pairings no type system sees, like a GST rate table with euro display settings.
  • A DI container profile. A Spring profile or Guice module binding all three interfaces together is this pattern in configuration. Best when the variant is fixed per process; worst when it is per request.

Abstract Factory vs Factory Method vs Builder vs Prototype vs Bridge

All five hand you an object you did not new yourself. What separates them is how many objects are involved, and who decides:

Pattern Intent Tell
Abstract Factory Create several related products and guarantee one family You hold a factory object, and which one you hold decides the whole set
Factory Method Let a subclass decide which single product to create One product, one create method, chosen by which subclass is running
Builder Assemble one complex product across several calls The calls accumulate into one object and end in build()
Prototype Produce a new object by copying an existing one No type is named at the creation site; the source instance carries the config
Bridge Split an abstraction from its implementation so both vary It consumes created objects rather than creating them, and often gets its implementor from an Abstract Factory

State the standard relationship before you are asked: an Abstract Factory’s methods are usually Factory Methods, so the two compose rather than compete. createTaxCalculator() alone is a factory method; the Abstract Factory groups three of them and thereby names the invariant. Builder is orthogonal the same way, and a Builder with four interdependent setters still has no answer for “do these three separate objects match?”.


When to Use vs When to Avoid

Use Abstract Factory When Avoid When
Two or more products must share a variant, and mixing them is a real bug No cross-product constraint exists – one factory method or a map of suppliers says it with less code
New families arrive regularly and the product list is stable You are still discovering which products the family needs
Each family needs construction arguments the call site should not see Only one family exists and none is on the roadmap – that is an interface with one implementation
Tests need to swap the whole set at once rather than stub three things Callers are meant to choose independently, like a payment method and a UI language
The variant is picked once per request or tenant, then used downstream A container or config already groups the bindings and nobody constructs these by hand

Two failure modes. The one-family abstract factory is an interface with a single implementation whose three methods each wrap one new; it prevents nothing, because there is no second family to mix with; delete the interface until one shows up. The other is harder to undo: the factory grows unrelated methods and becomes a service locator – createAuditLogger(), then createHttpClient(), then createClock() – until you have a god object whose members share nothing but a create prefix and “family” names no constraint anybody could state. The guard is one line: every method must return a product some single caller uses together with the others. Over-Engineering has the broader version.


Interview Questions

  1. “Abstract Factory vs Factory Method – what is the actual difference?” – Count the products. Factory Method creates one and the variation comes from which subclass is running; Abstract Factory creates several related ones and the variation comes from which factory object you hold. The difference that matters is the guarantee that the products match: if removing the pattern lets someone pair product A from variant 1 with product B from variant 2 and still compile, you need Abstract Factory. No pair to mismatch means Factory Method is enough.

  2. “You need to add a fourth product to the family. What happens?” – The build goes red in every concrete factory, which is the pattern’s known cost: new families are cheap, new products are expensive. A default method keeps everything compiling but silently ships a wrong default – fine for a logger, unacceptable for money. Splitting the family into TaxFactory and ComplianceFactory works when the new product is only cohesive with a subset. For a tax-adjacent product, take the red build on purpose: twenty compiler errors naming twenty files beats one defaulted tax rule nobody notices.

  3. “Doesn’t a DI container make this obsolete?” – It makes the wiring obsolete, not the constraint. A Spring profile or Guice module binding all three interfaces to the Indian implementations is this pattern spelled in configuration: the container is the registry, the module is the concrete factory, and the guarantee has moved to a startup check. Two cases still want the hand-written version – when the variant is chosen per request rather than per process, which containers model awkwardly, and when you want a compile error instead of a boot-time one.

  4. “How do you test code that depends on a family?” – One fake factory returning fakes replaces three separate stubs, the payoff people forget to mention. The double is one line in modern Java: a record FakePaymentFactory(TaxCalculator tax, CurrencyFormatter fmt, ComplianceValidator compliance) implements RegionalPaymentFactory. Then add the one test the pattern actually needs: loop over every registered factory and assert that the currency its formatter emits matches the regime its tax calculator applies, because a concrete factory is the only place left where a family can be assembled wrongly. Testing for Machine Coding covers the shape.

  5. “Where does the factory selection itself live?” – At the edge, exactly once. A Map<Region, RegionalPaymentFactory> built at startup and left immutable beats a switch: a switch gets copy-pasted and each copy drifts, while the map is where a new region plugs in. Resolve it in the layer that already knows the region, then pass the factory down. Resolving per object is the bug the pattern was introduced to fix – a lookup at every call site is the original createTaxCalculator(region) problem wearing a map. An unknown key throws, because a default region is how you ship Indian tax rules to Germany.


See It in Action

  • Discount Engine – a market’s rule parser, rounding policy and currency formatter are one family; rounding by another market’s convention is wrong on every order
  • Notification Service – one family per channel: transport, template renderer and rate limiter, the set the Bridge lesson hands off
  • Mini ORM – dialect families, where connection, query builder and migration runner must be one vendor or the generated SQL is valid for nobody
  • Vending Machine – a market’s cash family: denominations, note validator and change maker. A rupee coin set with a euro change maker returns coins the machine does not stock