Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Abstract Factory

Intent

Provide one doorway that builds a whole matching set of related parts so clients never mix incompatible pieces.

Motivation

A UI kit ships buttons and checkboxes that must match: light theme parts go together, dark theme parts go together. Scattering if theme == dark through the app mixes light buttons with dark boxes. An abstract factory returns a theme-consistent family from one call, and the app only talks to abstract button and checkbox roles.

Structure

flowchart LR
  App --> Factory[Theme Factory]
  Factory --> Light[Light Theme Factory]
  Factory --> Dark[Dark Theme Factory]
  Light --> LB[Light Button]
  Light --> LC[Light Checkbox]
  Dark --> DB[Dark Button]
  Dark --> DC[Dark Checkbox]
  • Abstract factory — creates button + checkbox without naming concrete kinds.
  • Concrete factories — Light and Dark factories returning matching pairs.
  • Abstract products — Button, Checkbox roles; concrete products fill each theme.

Consequences

  • Benefit: theme consistency by construction; swapping themes swaps one factory.
  • Cost: adding a new product kind (e.g., slider) touches every factory.

Basic Recap

Abstract Factory creates a compatible family of products without exposing their concrete classes to the client. One factory supplies related objects, such as a queue, storage bucket, and network policy for the same platform. The client depends on the family interfaces and avoids mixing implementations that cannot work together. This is broader than Factory Method: the central guarantee is consistency across several created products.

Complex Scenario

A deployment service provisions an isolated environment for each customer. A cloud-specific factory creates the network, message queue, and artifact store, and an environment planner wires them into one topology. Selecting each resource independently could pair a private network from one provider with credentials or endpoints from another. The factory should return a validated bundle whose region, encryption policy, and identity model agree.

Edge cases

  • Partial failure: The network may exist when queue creation fails; the planner needs a provisioning journal and cleanup policy rather than treating factory return as an atomic transaction.
  • Retries: Re-running creation must reuse environment-scoped names and idempotency tokens so it adopts existing resources instead of duplicating them.
  • Concurrency: Two planners must not independently initialize a shared factory cache and publish half-initialized client bundles to other threads.

Family validation belongs before any remote calls where possible, because an abstract factory cannot make distributed provisioning atomic.

Sketch (illustrative pseudocode, not runnable):

EnvironmentPlanner.provision(request):
    factory = factories.for(request.platform, request.region)
    plan = factory.describeFamily(request.environmentKey)
    validateCompatibility(plan)

    journal = ProvisioningJournal.open(request.environmentKey)
    network = factory.createNetwork(plan, journal)
    queue = factory.createQueue(plan, journal)
    store = factory.createArtifactStore(plan, journal)

    bind(network, queue, store, journal)
    return Environment(network, queue, store, journal)

When to Use / When Not to Use

Use when:

  • Several related parts must vary together as a family.

Avoid when:

  • Only one product kind exists or families never change together.

Examples

  • examples/elixir/abstract-factory/
  • examples/dart/abstract-factory/
  • examples/go/abstract-factory/
  • examples/rust/abstract-factory/

Expected outcome: rendering light then dark prints a matched button + checkbox line per theme.

Anti-pattern / Failure Mode

  • Misuse: Forcing a family abstraction over products that never need to match.

  • Review signal: Families where callers mix parts from different variants.

  • Misuse symptom: A factory returns unrelated utilities, or callers routinely combine products from different factories and patch incompatibilities with conditionals. Another symptom is one implementation and one product, where a whole family abstraction merely mirrors constructors.

  • Review signal: Watch for provider names appearing in client branches, cross-family casts, and configuration tests that only check individual objects rather than their compatibility. Provisioning logs containing repeated resource names after retries indicate that the factory is hiding construction but not preserving environment identity.

Exercise

Add a high-contrast factory producing its own button + checkbox without editing client render code.

Self-check

  • What breaks if you mix factories?
    AnswerTheme mismatch — a light button with a dark checkbox — which the pattern prevents by sourcing both from one factory.
  • How is this different from Builder?
    AnswerFactory delivers a ready family at once; Builder assembles one complex thing step by step.