Pattern 16/22 · Creational

Abstract Factory

A single factory creates an entire family of related products (Button + Input + Card of the same theme), so the client can no longer accidentally mix products from two different families.

Creational●●●13 min read8 stepsalso known as: Kit, Widgets, Factory of factories
creationalproduct familythemeplugincomposition rootdriver

01 — It starts with code that is breaking

Problem

You're building a design system. First rule: nobody writes <button class="..."> by hand; it has to go through createButton(variant) so the CSS classes are always right. One function, one parameter, clean. That's Factory Method, and it's serving you well.

Six months later, design wants the whole family in sync: button, input, card, badge, toast. You add createInput(variant), createCard(variant) — each still its own factory function, still tidy. Then SettingsForm.vue renders a black button right next to a white input. Investigation: the button's variant comes from the component's prop, while the input gets it from the useTheme() composable — two different paths, and on that screen they don't hold the same value.

Nobody wrote wrong logic. The problem is that the shape of the code allows you to take a button from one family and an input from another, and TypeScript stays completely silent, because createButton returns Button and createInput returns Input — two independent interfaces, with no constraint saying "these two must come from the same source". An ugly screenshot is the early symptom; the real bugs of this kind are much quieter.

The backend version of the same story hurts a lot more. You write createConnection(dialect), then need createQuoter(dialect) to quote column names, then createMigrator(dialect). Three separate factories, dialect passed three times. One variable-renaming refactor later, one file still says "mysql" while the other two say "postgres". Postgres does not quote identifiers with backticks, so the SQL runs, returns an empty result, and raises no error anywhere. You debug for two days to arrive at the conclusion: the broken thing was created in a different file, a long time ago.

The lesson: when there's only one product, Factory Method covers everything. When products come in families and constrain each other, you need a unit of code that represents the "family" itself — not three factories all reading the same string from context.

02 — The idea, before touching code

Solution

The paradox: you call db.selectFrom(...) and get back correct Postgres SQL. What do you do differently on MySQL? Nothing — you change one line of setup. That's Abstract Factory: a single object whose interface lists every way to create things in the family (createAdapter(), createDriver(), createIntrospector(), createQueryCompiler()), and each dialect implements that whole list.

Structure: a UIFactory interface with button(), input(), card(); one object per family: dark, light, hc. The client receives one factory and gets everything from it, so it can no longer mix families. The number of branching points shrinks to one — the composition root, where you read the theme from config and pick the object.

Drop the "factory of factories" image from your head right now. In TypeScript, an Abstract Factory is usually just an interface describing the contract of a plugin/driver/theme, with each family being an object literal that matches that contract. If your family has exactly ONE product, this isn't Abstract Factory — it's Factory Method, and you've just added a useless wrapping layer. This pattern only makes sense when products come in pairs or more and they absolutely must fit together.

03 — Doing it for real, one code fragment per step

Step by step

1

Name the families and each family's products before writing code

Abstract Factory stands or falls at this step, not at the coding step. Write it down: a family is something you pick once and use all year (theme, platform, database dialect). A product is something you create many times during a session (button, input, connection, quoter).

The legitimacy test: is there any situation where two products from different families appear on the same screen or in the same transaction? If there is and the system still works correctly, the family is fake — don't use this pattern.

textinventory.md
Family (picked once at boot)   Product (created often)    Constraint between products
---------------------------    -----------------------    ---------------------------
theme: dark                    button, input, card        same palette, same radius
theme: light                   button, input, card        same palette, same radius
dialect: postgres              connection, quoter, SQL    "col", not backticks
dialect: mysql                 connection, quoter, SQL    backticks, different LIMIT
The last column is what decides it. No cross-product constraint, no Abstract Factory.
Key pointA product family exists when the products share a common invariant (palette, syntax, protocol version) that breaks if you mix families.
2

Write an interface for each product, as usual

Nothing special yet. One small interface per product, describing exactly what the client needs to use — nothing more. Remember that a product interface on its own can't prevent family mixing, so don't try to stuff family information into it:

tsproducts.ts
export interface Button {
  readonly kind: string
  render(label: string): string
}

export interface Input {
  readonly kind: string
  render(placeholder: string): string
}

// Don't do this: encoding the "family" into each product's type.
// type DarkButton = Button & { theme: 'dark' }
// -> you'd have to repeat it for every product, and nothing cross-checks them.
Key pointA product interface only says what the product does. Where the product comes from is the factory's business, and that's exactly where the pattern lives.
3

Declare the interface for the WHOLE FAMILY — this is the pattern step

One interface, one method per product. The return type is the product interface, not a concrete class. This interface is what prevents family mixing, because the client can only get products from a single object:

tsui-factory.ts
export interface UIFactory {
  readonly name: string
  button(): Button
  input(): Input
  card(): Card
}

// The constraint now lives in the TYPE: a UIFactory must return
// a button + input + card that "belong together", and the client
// has no other way to get them.
Compare: three separate createButton/createInput/createCard functions allow 3 different theme sources. One object doesn't.
Key pointGoing from "N functions all reading one variable" to "one object as the single source" — that's the entire anti-mixing mechanism, nothing mystical.
4

Implement one factory per family, as an object literal

TypeScript gives you the cleanest version of the pattern without a single class: an object literal declared with satisfies UIFactory. A missing method is a compile error right in that family's file — not at runtime.

tsdark.ts
import type { UIFactory } from './ui-factory'

export const dark = {
  name: 'dark',
  button: () => ({
    kind: 'dark-btn',
    render: label => '<button class="btn--dark">' + label + '</button>',
  }),
  input: () => ({
    kind: 'dark-input',
    render: ph => '<input class="input--dark" placeholder="' + ph + '">',
  }),
  card: () => ({
    kind: 'dark-card',
    render: title => '<div class="card--dark">' + title + '</div>',
  }),
} satisfies UIFactory
The GoF version uses an abstract class + one subclass per family; in TS, an object literal + satisfies gives the same safety with less ceremony.
Key pointUse satisfies rather than : UIFactory if you want to keep the narrow literal type; use : UIFactory when you want to force exactly the interface.
5

Let the client receive exactly one factory

The code consuming the products must not pick the family itself. It receives the factory as a parameter/prop, and every product it displays comes out of that one object. This is where the pattern pays off:

tssettings-form.ts
import type { UIFactory } from './ui-factory'

export function renderSettingsForm(ui: UIFactory): string {
  // Mixing families is IMPOSSIBLE here: there is no second source.
  return ui.button().render('Save') + ' || ' + ui.input().render('Email')
}

// The Vue version: a typed InjectionKey, provided once by a parent.
export const UI_KEY = Symbol('ui') as InjectionKey<UIFactory>
// app/plugin:  provide(UI_KEY, pickUI(useRuntimeConfig().theme))
// component:   const ui = inject(UI_KEY)!   // no other way in
Key pointIf a component still takes a separate variant/theme variable to pick for itself, you've disabled the pattern: the single source has become two sources again.
6

The only place allowed to branch: the composition root

One file. Read env/config/user preference, pick the object, hand it to the app. Every other if (theme === ...) in the codebase is a smell:

tsnuxt-ui-factory.ts
// server/utils or a plugin: EXACTLY ONE place picks the family.
import { dark } from './ui/dark'
import { light } from './ui/light'
import { highContrast } from './ui/hc'

const families = { dark, light, hc: highContrast } as const

export function pickUI(mode: string): UIFactory {
  const found = families[mode as keyof typeof families]
  if (!found) throw new Error('Theme does not exist: ' + mode)
  return found
}

// app/plugin/ui.ts:
// provide(key, pickUI(useRuntimeConfig().theme))
Key pointAudit with grep: if theme/variant/dialect shows up in business code instead of only in the composition root, the product family is leaking.
7

The real price: adding a product to the family

This is Abstract Factory's classic weak spot, and you should know it before you commit. Add a switch() method to UIFactory ⇒ every existing family immediately fails to compile. The pattern is closed for new families (add an hc.ts file: easy) but open in the wrong direction for new products (change the interface: painful).

This cost is real and no trick makes it go away. You only get to choose where it hurts: either a new family costs 1 line, or a new product costs N files.

tsadd-product.ts
interface UIFactory {
  button(label: string): Button
  input(placeholder: string): Input
  switch(name: string, on: boolean): Toggle   // <- new
}
// dark.ts, light.ts, hc.ts: all three go red. Exactly when you want to see it.

// Ease the pain (it won't go away): a base factory provides defaults, each family spreads it in.
const base = { switch: (name: string) => ({ kind: 'toggle', render: () => name }) }
export const dark = { ...base, button: () => ({ render: l => l }), input: () => ({ render: p => p }) }
// the old dark.ts stays red until it implements switch().
Key pointIf your product list still changes every month, that's a sign you picked the wrong pattern — consider a registry of individual products instead.
8

Cut the ceremony: it's just a plugin contract

Strip away the GoF names and what you've written is: an interface describing a plugin, and each plugin is an object matching that interface. Kysely calls it a Dialect, other ORMs call it a Driver, bundlers call it a Plugin, Nuxt calls it a module with runtimeConfig. You've been using Abstract Factory every week without naming it.

Recognizing this saves you from two accidents: building nested "factories of factories" (a factory returning a factory — you won't be able to read your own code anymore), and creating an interface for a family with only one member.

tswhat-kysely-really-is.ts
// Excerpt from Kysely's real API: one family = 4 products that go together.
interface Dialect {
  createAdapter(): DialectAdapter
  createDriver(): Driver
  createIntrospector(db: Kysely<any>): DatabaseIntrospector
  createQueryCompiler(): QueryCompiler
}

const db = new Kysely<Db>({ dialect: new PostgresDialect({ pool }) })
// You don't pick a "quoter" separately, or a "compiler" separately.
// One family, one decision, in one place.
Key pointIf you name an interface ...Factory and it has only one method, you're not writing Abstract Factory — you're writing Factory Method and should call it by its real name.

04 — Who talks to whom

Structure

  • AbstractFactoryThe interface declaring **the whole family**: `button()`, `input()`, `card()`. This is what the client sees.
  • AbstractProductThe interface of each product: `Button`, `Input`, `Card`. The client uses only these interfaces.
  • ConcreteFactoryOne family: `dark`, `light`, `hc`. Implements every method, and only creates products of its own family.
  • ConcreteProductDarkButton, DarkInput, HcCard. Knows nothing about other families and doesn't need to.
  • ClientThe render/query process that receives **one** factory and gets every product from it. Contains no concrete class names.
                      ┌─────────────────────────────┐
  Client ── 1 object ─►│ AbstractFactory: UIFactory  │
  renderForm(ui)       │  button(label): Button      │
                       │  input(ph): Input           │
                       └───────┬──────────────┬──────┘
                     ┌─────────┘              └──────────┐
                     ▼                                   ▼
               DarkFactory                          LightFactory
               button() ──► DarkButton              button() ──► LightButton
               input()  ──► DarkInput               input()  ──► LightInput
             └── every product comes out of the same object ──┘
                mixing families isn't a compile error, it CAN'T HAPPEN

05 — Edit freely, run it right here

Try it: three families, one client, no way to mix

tsdemo.ts
interface Button { render(): string }
interface Input { render(): string }

interface UIFactory {
  readonly name: string
  button(label: string): Button
  input(placeholder: string): Input
}

const dark: UIFactory = {
  name: 'dark',
  button: label => ({ render: () => '<button class="btn--dark">' + label + '</button>' }),
  input: p => ({ render: () => '<input class="input--dark" placeholder="' + p + '">' }),
}

const light: UIFactory = {
  name: 'light',
  button: label => ({ render: () => '<button class="btn--light">' + label + '</button>' }),
  input: p => ({ render: () => '<input class="input--light" placeholder="' + p + '">' }),
}

// A third family: just add 1 object, no client changes.
const highContrast: UIFactory = {
  name: 'hc',
  button: label => ({ render: () => '<button class="btn--hc">' + label + '</button>' }),
  input: p => ({ render: () => '<input class="input--hc" placeholder="' + p + '">' }),
}

// Composition root: the ONLY place that picks the family.
const families: Record<string, UIFactory> = { dark, light, hc: highContrast }

// Client: not a single concrete product name leaks in here.
const renderForm = (f: UIFactory): string =>
  f.button('Save').render() + ' || ' + f.input('Email').render()

for (const key of ['dark', 'light', 'hc']) {
  const f = families[key]
  console.log('[' + f.name + '] ' + renderForm(f))
}
console
[dark] <button class="btn--dark">Save</button> || <input class="input--dark" placeholder="Email">
[light] <button class="btn--light">Save</button> || <input class="input--light" placeholder="Email">
[hc] <button class="btn--hc">Save</button> || <input class="input--hc" placeholder="Email">

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • Products come in families of 2+ members that share constraints: same palette, same SQL dialect, same protocol version, same encoding.
  • You want to swap out an entire product family at startup or via config (theme, platform, environment, tenant) without touching business code.
  • You want one single place that contains concrete class names (the composition root), so the rest of the repo talks only through interfaces.
  • You're designing a plugin/driver API for others to implement: the plugin contract is the Abstract Factory, and they register the whole family rather than individual pieces.
  • Mixing products from different families produces silent errors (SQL returning empty, rendering off-theme, missing data) instead of a clear exception — this is the strongest signal.

Don't use it when

  • Over-engineering is this pattern's number one failure. Does the family have exactly ONE product? Then it's Factory Method, and the factory object is just a wrapper adding no information. Count the products first, then name the pattern.
  • Adding a product to the interface breaks compilation for every existing factory. That's a design cost, not a bug: if your product list still changes every month, Abstract Factory is the wrong shape.
  • Passing a factory down through 4 layers and then "conveniently" grabbing another product at the bottom is the shortest road to a service locator: a component calling ui.button() and ui.reportWriter() on the same giant object. Each layer should receive only what it uses — split out smaller interfaces.
  • The types are only safe when the interface is narrow. A UIFactory that returns any, or a client that still takes a separate variant to pick for itself, and you lose all the anti-mixing protection and are left with just ceremony.
  • Don't nest factories: a factory creating factories, which then read the parent factory's config. Three months later nobody can answer "who created this object". If you need several independent families, give each its own factory and wire them together in the composition root.

07 — You have met it already, just not by name

In real code

Kysely: the Dialect interface

A real contract, in dialect/dialect.ts: createAdapter(), createDriver(), createIntrospector(db), createQueryCompiler(). PostgresDialect returns the set of four Postgres products, MysqlDialect returns the set of four MySQL products. You never pick a quoter or compiler separately — that's exactly the point of the pattern.

TypeORM: one Driver per dialect

PostgresDriver, MysqlDriver, CockroachDriver... each handles its own connection pool (createPool), escapes identifiers using its own database's syntax (Postgres uses double quotes, MySQL uses backticks), and generates its own SQL. Choosing a driver means choosing the whole family; there's no API to grab MySQL's quoter and plug it into a Postgres connection.

Playwright: chromium / firefox / webkit

Each BrowserType produces a consistent family of objects: Browser → BrowserContext → Page → Locator, all internally compatible with each other. Your tests are written once and run against three families by changing exactly one setup line.

Nuxt/Vue: a theme object via provide with an InjectionKey

The healthy way to theme an entire component tree: a theme object (color tokens, radius, classes) is provided once with an InjectionKey<UIFactory>, and components only read from it. Same principle: one single source for the whole family, no component picks its own variant.

08 — Try it yourself

Exercise

You have `createButton(v)`, `createInput(v)`, `createCard(v)` and a component that has rendered a dark button next to a light input. Convert it to Abstract Factory with three families `dark`, `light`, `hc`, such that (a) mixing can no longer be written, (b) there is exactly 1 place that compares the theme, (c) adding the `hc` family requires changing no components.

Hints, open them one at a time:

  1. Write a UIFactory interface with name, button(), input(), card(). Notice that the component no longer takes a variant.
  2. One file per family, export const dark = { ... } satisfies UIFactory. Adding a family = adding a file.
  3. Collect everything into pickUI(mode): UIFactory in one file, then provide(key, pickUI(...)) once in a plugin. Delete every remaining if (mode === ...).

Define UIFactory; one object literal per family matching the interface; the component receives the factory via prop/inject and no longer has any variant parameter. pickUI(mode) is the only place that maps a string to an object, and it throws on an unknown key. Adding hc = one new file + one line in the map. To prove mixing has no way in: try writing dark.button() next to light.input() in the same render function — you'll see there's no way to call both, because render only receives exactly one object.

tsexercise.ts
interface Button { render(label: string): string }
interface Input { render(placeholder: string): string }

interface UIFactory {
  readonly name: string
  button(): Button
  input(): Input
}

const dark = {
  name: 'dark',
  button: () => ({ render: l => '<btn dark>' + l + '</btn>' }),
  input: () => ({ render: p => '<input dark ph=' + p + '>' }),
} satisfies UIFactory

const light = {
  name: 'light',
  button: () => ({ render: l => '<btn light>' + l + '</btn>' }),
  input: () => ({ render: p => '<input light ph=' + p + '>' }),
} satisfies UIFactory

const hc = {
  name: 'hc',
  button: () => ({ render: l => '<btn hc>' + l + '</btn>' }),
  input: () => ({ render: p => '<input hc ph=' + p + '>' }),
} satisfies UIFactory

// The ONLY place that picks the family.
const families: Record<string, UIFactory> = { dark, light, hc }
export function pickUI(mode: string): UIFactory {
  const f = families[mode]
  if (!f) throw new Error('Theme does not exist: ' + mode)
  return f
}

// Client: one parameter, no door for mixing.
const renderForm = (ui: UIFactory) => ui.button().render('Save') + ' ' + ui.input().render('Email')

for (const m of ['dark', 'light', 'hc'])
  console.log(m + ': ' + renderForm(pickUI(m)))

09 — Read them in pairs to see the essence

Related patterns

  • Factory MethodFactory Method creates ONE product and lets subclasses choose; Abstract Factory is a *set* of factory methods that are forced to go together. Multi-product families are usually declared as a set of factory methods.
  • BridgeEasy to confuse: Bridge splits a class into two hierarchies, abstraction and implementation, and connects them via composition; Abstract Factory produces a whole family of those implementations. Bridge says "how to connect them", Abstract Factory says "who creates which set".
  • SingletonA concrete factory has no state, so it's usually used as an exported constant (`export const dark`), or a singleton registered at the composition root — GoF explicitly notes this pair often goes together.
  • PrototypeInstead of each concrete factory calling `new` for every product, it can clone template instances. Adding a new family is sometimes just registering a set of prototypes, no new code needed.