Design patterns reference

The classic design patterns, without the class hierarchies.

The 1994 Gang of Four catalogue was written for languages without first-class functions or union types. The problems it names still come up in every codebase, but the solutions are usually smaller in TypeScript. This reference covers nine patterns, the problem each one solves, and the shape it takes today.

creational

Factory

A factory is a function that decides which object to build and how, so callers ask for what they need without importing concrete classes or repeating construction logic. In TypeScript it is usually a plain function that returns an interface. The Factory Method and Abstract Factory variants exist mainly to get the same effect in languages without first-class functions.

Use it for

  • Choosing an implementation from configuration or environment: a real mailer in production, an in-memory one in tests.
  • Construction that needs validation, defaults, or several collaborators wired together.

Watch for

  • A factory with one product and no decision to make is a constructor with extra steps.
  • A switch over a growing list of types inside the factory becomes the place every change collides. A registry — a record of builders keyed by type — keeps each addition local.
interface Mailer {
  send(to: string, body: string): Promise<void>
}

export function createMailer(env: Env): Mailer {
  if (env.NODE_ENV === "test") return memoryMailer()
  return smtpMailer({ host: env.SMTP_HOST, apiKey: env.SMTP_KEY })
}

creational

Singleton

A singleton guarantees one instance of something — a connection pool, an SDK client, a configuration object — and one place to get it. In JavaScript every module is evaluated once, so an exported constant is already a singleton without the pattern. The decision that matters is when the instance gets created.

Use it for

  • Expensive shared resources: connection pools, SDK clients, caches.
  • Lazy construction on first use, so importing a module never opens a connection or reads a secret.

Watch for

  • Constructing at import time runs during builds, tests, and prerendering, often before environment variables exist. Construct lazily inside a getter.
  • Global mutable state makes tests depend on their order. Expose a reset for tests, or pass the instance in instead of importing it.
  • Hot reloading in development re-evaluates modules and creates new instances. Pools leak connections unless the instance is cached on globalThis in development.
  • In serverless runtimes a module-level instance lives as long as the warm instance, not the request. Never keep per-user state on it.
// Eager: runs on import, including during builds and tests
// export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)

// Lazy: one instance, created on first use
let client: Stripe | undefined

export function stripe(): Stripe {
  client ??= new Stripe(requireEnv("STRIPE_SECRET_KEY"))
  return client
}

structural

Adapter

An adapter converts one interface into the one your code expects. It sits at the boundary with something you do not control — a vendor SDK, a legacy module, another API version — and translates names, shapes, units, and errors, so the rest of the codebase speaks one vocabulary.

Use it for

  • Wrapping a third-party SDK behind an interface named in your own domain’s terms.
  • Normalising several providers — payments, storage, AI models — to one shape so they can be swapped.
  • Turning external error codes into your own error types at the edge.

Watch for

  • An adapter that passes the vendor’s types straight through has adapted nothing; those shapes still spread across the codebase.
  • Adapting to the lowest common denominator hides capabilities you need. Expose them explicitly instead of pretending every provider is identical.
// What the app wants, in its own terms
interface Geocoder {
  locate(address: string): Promise<{ lat: number; lng: number } | null>
}

// The vendor's shape stays inside the adapter
export const acmeGeocoder = (sdk: AcmeClient): Geocoder => ({
  async locate(address) {
    const res = await sdk.forwardGeocode({ query: address, limit: 1 })
    const hit = res.features[0]
    if (!hit) return null
    const [lng, lat] = hit.center // the vendor uses [lng, lat]
    return { lat, lng }
  },
})

structural

Decorator

A decorator wraps a function or object with the same interface and adds behaviour before or after the call — logging, caching, retries, authorization, timing — without changing the wrapped code. In TypeScript it is most often a higher-order function, and a middleware chain is a sequence of decorators.

Use it for

  • Concerns shared by many functions: withRetry(fn), withCache(fn), withAuth(handler).
  • Adding behaviour per environment, such as wrapping a client with tracing in production only.

Watch for

  • Order matters. A cache outside a retry caches the eventual success; a retry outside a cache retries cache misses. Decide which you mean.
  • Deep stacks of wrappers make stack traces and inferred types hard to read. Keep the chain short and name each layer.
  • TypeScript’s @decorator syntax is a separate language feature for annotating classes. It can apply this pattern, but the pattern does not need it.
type Handler = (req: Request) => Promise<Response>

const withTiming =
  (name: string, next: Handler): Handler =>
  async (req) => {
    const start = performance.now()
    try {
      return await next(req)
    } finally {
      console.info(name, Math.round(performance.now() - start), "ms")
    }
  }

export const POST = withTiming("orders.create", withAuth(createOrder))

structural

Facade

A facade puts one simple interface in front of a complicated subsystem. Callers ask for an outcome — upgrade a plan, publish a site — and the facade runs the lower-level calls in the right order with the right error handling. The subsystem stays available for the rare caller that needs it directly.

Use it for

  • A module’s public index.ts: a few functions in front of many internal files.
  • Multi-step workflows over an SDK that callers would otherwise reassemble, slightly differently, in five places.

Watch for

  • A facade that grows a method for every subsystem function is the subsystem again, plus one layer.
  • Hiding failures the caller has to handle. A facade simplifies the happy path; it still has to report what went wrong in terms the caller can act on.
// billing/index.ts: the only file other modules import
export async function upgradePlan(uid: string, plan: Plan) {
  const customer = await customers.ensure(uid)
  const session = await checkout.create(customer, priceFor(plan))
  await audit.record(uid, "plan-upgrade-started", { plan })
  return session.url
}

behavioral

Strategy

Strategy makes an algorithm interchangeable: several implementations share one signature, and the caller picks one at runtime instead of branching inside a function. In TypeScript a strategy is a function, and a set of strategies is a record keyed by a union type, which lets the compiler check that every case has one.

Use it for

  • Pricing rules, sort orders, export formats, validation per country — anywhere a switch grows a branch per variant.
  • Letting tests inject a deterministic strategy, such as a fixed clock or a seeded random source.

Watch for

  • Strategies that need different inputs do not really share an interface. Forcing them into one produces optional parameters that only some of them read.
  • Two variants that will never become three are clearer as an if statement.
type Format = "csv" | "json" | "markdown"
type Exporter = (rows: string[][]) => string

const exporters: Record<Format, Exporter> = {
  csv: (rows) => rows.map((row) => row.join(",")).join("\n"),
  json: (rows) => JSON.stringify(rows),
  markdown: toMarkdownTable,
} // a Format without an exporter is a type error

export const exportRows = (format: Format, rows: string[][]) =>
  exporters[format](rows)

behavioral

Observer

An observable keeps a list of subscribers and notifies each one when something changes, so the source does not need to know who depends on it. DOM events, EventTarget, React’s useSyncExternalStore, and every state library are built on it.

Use it for

  • A small store shared by components or modules that must react when it changes.
  • Decoupling a source from a growing list of reactions inside one process — the in-process relative of event-driven architecture.

Watch for

  • Every subscribe needs an unsubscribe. A listener that is never removed keeps its component, and everything it closes over, alive.
  • Synchronous notification means one slow or throwing subscriber blocks or breaks the rest. Isolate errors per listener.
  • A subscriber that updates the source while being notified can loop. Notify only once the state change is complete.
export function createStore<T>(initial: T) {
  let state = initial
  const listeners = new Set<() => void>()
  return {
    get: () => state,
    set(next: T) {
      state = next
      listeners.forEach((listener) => listener())
    },
    subscribe(listener: () => void) {
      listeners.add(listener)
      return () => {
        listeners.delete(listener) // the unsubscribe
      }
    },
  }
}
// In React: useSyncExternalStore(store.subscribe, store.get)

behavioral

Command

A command turns an action into a value: an object that describes what to do and, often, how to undo it. Because it is data, it can be queued, logged, sent over the network, replayed, or pushed onto a history stack. Undo and redo, job queues, and Redux-style actions are all commands.

Use it for

  • Undo and redo: a history of commands, each able to apply and reverse itself.
  • Deferred or remote execution: background jobs, offline queues that sync later.
  • An audit trail: the log of commands is the record of who did what.

Watch for

  • Undo must restore exactly what the command changed. Capture the previous value when the command runs, not when it is created.
  • Commands kept in history hold whatever they reference. Store ids and plain values, not live objects.
interface Command {
  label: string
  apply(): void
  revert(): void
}

const rename = (id: string, name: string): Command => {
  let previous = ""
  return {
    label: `Rename to ${name}`,
    apply() {
      previous = nodes.nameOf(id) // captured when it runs
      nodes.rename(id, name)
    },
    revert() {
      nodes.rename(id, previous)
    },
  }
}

behavioral

State

The state pattern makes behaviour depend on which state something is in, with explicit transitions between states. In TypeScript its most useful form is a discriminated union plus a transition function: each state carries only the data valid in it, so impossible combinations — loading with both an error and a result — cannot be represented.

Use it for

  • Request lifecycles: idle, loading, success, error.
  • Workflows with rules about what may happen next: draft, in review, published.
  • UI modes — editing, dragging, selecting — that each handle the same events differently.

Watch for

  • A cluster of booleans (isLoading, isError, hasData) allows combinations that should be impossible. Replace them with one status field.
  • Transitions scattered across event handlers. Keep them in one function, so the allowed moves can be read and tested in one place.
  • Machines with nested or parallel states are where a library such as XState earns its weight. A union and a switch cover most interfaces.
type Upload =
  | { status: "idle" }
  | { status: "uploading"; progress: number }
  | { status: "done"; url: string }
  | { status: "failed"; error: string }

function next(state: Upload, event: UploadEvent): Upload {
  switch (state.status) {
    case "idle":
      return event.type === "start" ? { status: "uploading", progress: 0 } : state
    case "uploading":
      if (event.type === "progress") return { ...state, progress: event.value }
      if (event.type === "finish") return { status: "done", url: event.url }
      if (event.type === "error") return { status: "failed", error: event.message }
      return state
    default:
      return state // done and failed accept no events
  }
}

Start from the problem

Tests need a fake version of a real service
Factory
A client created at import time breaks the build
Singleton
A vendor SDK’s types have spread through the codebase
Adapter
Every handler repeats the same logging and auth code
Decorator
Five callers each rebuild the same multi-step SDK workflow
Facade
A switch statement grows a branch for every new variant
Strategy
Several parts of the app must react when one value changes
Observer
The app needs undo, a job queue, or an action log
Command
isLoading, isError, and data disagree with each other
State

Keep going

React components have patterns of their own.

The React patterns reference covers composition, compound components, controlled inputs, custom hooks, state colocation, context, and the server–client boundary.

Open the React patterns reference

With your permission, Affonso uses a 30-day cookie to remember which affiliate referred you. Google Analytics measures site usage. Google Ads measures our advertising. Microsoft Clarity records masked session replays. You can use Nodlume with or without these cookies.