Pattern 04/22 · Creational

Factory Method

Wrap the "which class do I new up" decision in a single method or function, so the call site only declares what it needs, and the choice of implementation is made at runtime by a subclass, config or registry.

Creational●●○11 min read8 stepsalso known as: Virtual Constructor; the function version is usually called Simple Factory / Factory Function
creationalnewfactory functioninheritancecomposition rootdependency injection

01 — It starts with code that is breaking

Problem

Task: let users download reports. The first export route takes exactly five minutes: fetch the rows, const exporter = new CsvExporter(), then res.send(exporter.render(rows)). Nobody complains: CsvExporter is a clean class, tested, does one thing, and anyone can write new in their sleep.

Then product wants JSON and PDF. The route grows three if branches, each with its own new. Meanwhile the "export data" feature is requested in five places: the admin page, the end-of-day cron job, the public API, an internal CLI, and the customer reporting module. By now new CsvExporter() lives in 12 different files, copy-pasted around an if (format === ...).

One Friday afternoon, CsvExporter needs new delimiter and timezone constructor parameters. You fix 12 places, type-check is green, you deploy. Thirty minutes later an alert fires: two places in the old reporting module still pass the old signature, and they sit inside an any-typed object so TypeScript can't see them. None of the 12 places you fixed is broken; the bug is in 2 places you didn't know existed.

The same story repeats with infrastructure: dev uses a SQLite file, staging uses a Postgres read replica, prod uses a pool with ssl: true. The new Pool(connectionString) call sits right inside the service class. The result: unit tests have to spin up a real database too, and every change to how connections are opened is a find-and-replace across the whole repo.

The problem isn't that new is bad. The problem is that new CsvExporter() is a literal: it welds the calling file to one specific file and freezes the "which class" decision at the moment you type it. Everything that comes later (new formats, new environments, another team's plugin) forces you to go back and edit that frozen spot.

02 — The idea, before touching code

Solution

Change the question the call site asks. Instead of "create a CsvExporter", the call site asks "give me an exporter for this format". The new moves into its own method; the caller only sees the ReportExporter interface. From then on, adding a format means editing one place, and that place is the only one allowed to know class names.

The real power of the GoF version is in the word method: because it's a method, subclasses can override it. The same run() process (fetch data → render → name the file → stream), but the public job picks based on the query while the audit job hard-codes JSON. It's Template Method's twin: a fixed process with exactly one step left open, except that step creates an object instead of computing something.

The version that survives long-term in TypeScript is much simpler: a plain function createExporter(format), or a Record<string, () => Exporter> map. No this, no prototype chain, tree-shakeable, testable by passing in a fake function. The abstract-class version costs you this-binding bugs when you turn methods into callbacks, and in exchange you get exactly one capability: subclasses get to choose the class. If you don't have subclasses, don't pay that price.

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

Step by step

1

First, count the `new`s and the types

Before abstracting anything, measure whether it's worth it. Run a grep for one kind of object and look at the number:

bashcount.sh
# How many places new up an exporter by hand?
rg -n "new (Csv|Json|Pdf)Exporter" src | wc -l
# 12

# How many files contain the "which exporter" decision?
rg -l "format === 'json'" src
# routes/report.ts  jobs/night.ts  cli/export.ts  ...
The number decides everything: 1 place and 1 type, do nothing. 12 places and 3 types, that's tech debt accruing interest.
Key pointFactory Method pays off when (number of types ≥ 2) × (number of call sites ≥ 2). Miss either condition and a direct new is the right call.
2

Pull `new` out into a function whose name states the intent

The first step needs no classes. Just move new into a function, and name the function after the business need, not after the class: createExporterFor(format), not makeCsvOrJson.

Look below: this is the entire "pattern" in its crudest form:

tscreate-exporter.ts
export interface ReportExporter {
  readonly format: string
  render(rows: Record<string, string | number>[]): string
  extension(): string
}

export function createExporter(format: string): ReportExporter {
  if (format === 'json') return new JsonExporter()
  if (format === 'pdf') return new PdfExporter()
  return new CsvExporter()
}
The three news now sit together. The word "single" starts to mean something: to find out what the system can export, you open one file.
Key pointThis step's goal is modest: every class-choosing decision is expressed in one place. No inheritance, no generics yet.
3

Make the factory return an interface, not a concrete class

Lots of people write function createExporter(f: string): CsvExporter | JsonExporter | PdfExporter. It looks more precise, but you've just escaped the pattern: the call site gets a union of concrete classes, so it's allowed to touch exporter.delimiter, and a month later you can no longer swap the implementation.

The return type must be an interface, i.e. something smaller than what all three classes can do. This isn't "abstraction principles" for show: the return type is the contract you're willing to keep stable.

tsreturn-type.ts
// Wrong: a union of concrete classes -> the caller knows too much
function createExporterBad(f: string): CsvExporter | JsonExporter {
  /* ... */
}

// Right: the caller sees exactly what the process needs
function createExporter(f: string): ReportExporter {
  /* ... */
}

const exporter = createExporter(query.format)
exporter.render(rows)      // OK
exporter.delimiter = ';'   // Compile error. Good: that's exactly the wall you want
Key pointFactory Method only isolates the call site if the return type is isolated too. Return a concrete class and removing new achieves nothing.
4

Rewrite the shared process until it's free of class names

Now fix the call sites. The criterion is mechanical: the body of the business function contains no concrete class names. If CsvExporter still appears, you're not done.

tsreport-service.ts
import { createExporter } from './create-exporter'

export class ReportService {
  handle(query: { format: string }, rows: Row[]) {
    const exporter = createExporter(query.format)   // <- the only place that "chooses"
    return {
      body: exporter.render(rows),
      contentType: CONTENT_TYPE[exporter.format],
      filename: 'report.' + exporter.extension(),
    }
  }
}
// Adding PdfExporter: this function doesn't change by a single character.
Note CONTENT_TYPE[exporter.format]: the process gets its information from data the exporter declares about itself, without knowing what class it is.
Key pointOpen/Closed is visible to the naked eye here: if adding a new type forces the shared process to change, class names are still leaking.
5

The GoF version: make it a method so subclasses get to choose

A factory function is enough for 80% of projects. But there are situations where you want subsystems to decide: you write ReportJob as the frame, and each kind of job (public, audit, partner) has its own format rules: audit must be JSON regardless of the query, the partner job is CSV only.

That's when createReport becomes an open method in an abstract class, and each subclass fills it in:

tsreport-job.ts
abstract class ReportJob {
  /** Factory Method: the open step. */
  abstract createReport(format: string): Report

  /** Template: fixed, no subclass may change it. */
  run(query: { format: string }, rows: Row[]): string {
    const r = this.createReport(query.format)
    return '[' + r.format + '] ' + r.render(rows)
  }
}

class PublicJob extends ReportJob {
  createReport(format: string) { return format === 'json' ? new JsonReport() : new CsvReport() }
}

class AuditJob extends ReportJob {
  createReport() { return new JsonReport() } // hard-coded, ignores the query
}
Same run(), two fates. This is what a plain factory function can't do, unless you give it a strategy parameter, and then you're back to the function version.
Key pointYou buy "subclasses choose the class" with a prototype chain, with this binding (callbacks losing this is a classic bug), and with lost tree-shaking. Buy it when you need it, not because the GoF diagram says so.
6

Pass the factory in, don't import it

Even with a factory function, your service still imports it directly, which means tests still run the production code and still open real connections. Turn the factory into a parameter and you get the cheapest test seam there is:

tstest-seam.ts
export class ReportService {
  constructor(
    private makeExporter: (format: string) => ReportExporter = createExporter,
  ) {}

  handle(query: { format: string }, rows: Row[]) {
    return this.makeExporter(query.format).render(rows)
  }
}

// prod: new ReportService() — the default is the real factory.
// test: no DB, no S3, no mocking library:
const svc = new ReportService(() => ({
  format: 'fake',
  extension: () => 'txt',
  render: () => 'MOCK',
}))
Key pointA default parameter = prod doesn't change at all; tests pass a 5-line fake object. This is Dependency Injection without a container.
7

Replace the switch with a registry when the list comes from data

In a real system, format doesn't come from code but from a query string, a settings.export_format column in the DB, an admin config someone just saved. At that point a long if/else chain is the wrong shape: you need a lookup. And this is also where another team's plugin can hook in without touching the core.

tsregistry.ts
type Format = 'csv' | 'json' | 'pdf'

const registry: Record<Format, () => ReportExporter> = {
  csv: () => new CsvExporter(),
  json: () => new JsonExporter(),
  pdf: () => new PdfExporter(),
}

export function createExporter(format: string): ReportExporter {
  const make = registry[format as Format]
  if (!make) throw new Error('Unsupported format: ' + format)
  return make()
}
// Note: the values are () => Exporter, not Exporter,
// so PdfExporter is only created when actually needed (it's heavy).
Key pointUse the Format union as the key, and throw loudly when nothing matches. Silently falling back to the first entry is how a typo becomes a wrong report sent to a customer.
8

Measure again: how many files does a new type cost

The acceptance test for this refactor isn't "the code looks nicer", it's a number. Add an XLSX format. How many files do you touch?

tsxlsx.ts
// A NEW file, plus exactly 2 registry lines + 1 union line.
import type { ReportExporter } from './create-exporter'

export class XlsxExporter implements ReportExporter {
  readonly format = 'xlsx'
  extension() { return 'xlsx' }
  render(rows: Record<string, string | number>[]) { /* exceljs */ return '' }
}

// registry.ts:  xlsx: () => new XlsxExporter(),
// type Format = 'csv' | 'json' | 'pdf' | 'xlsx'
If you still have to open ReportService.handle() to add an if, there's still a new or a string comparison in the wrong place. Go back to grep.
Key pointThe final measure: "add a type" = "add a file + one declaration line", not "edit N files and pray the tests cover all N branches".

04 — Who talks to whom

Structure

  • Product (Report)The interface every call site sees: `format`, `render(rows)`, `extension()`.
  • ConcreteProductCsvReport, JsonReport, PdfReport. None of them knows the others exist.
  • Creator (ReportJob)Declares the factory method as `abstract` and holds the shared process, which only uses the interface.
  • ConcreteCreatorPublicJob, AuditJob. Override the factory method; this is where the class-choosing rules live.
  • ClientCalls `job.run(query, rows)`. No concrete class name appears in its code.
Client ──► job.run(query, rows)        client only sees the interface
                  │
                  ▼
┌─────────────────────────────────────────────┐
│ Creator: abstract ReportJob                 │
│  + run(query, rows)                         │ <- fixed process
│     1. r = this.createReport(query.format)  │ <- the open step
│     2. return '[' + r.format + '] ' + ...   │
│  + {abstract} createReport(fmt): Report     │
└──────────────┬───────────────┬──────────────┘
        override         override
               ▼               ▼
        ┌────────────┐  ┌────────────┐
        │ PublicJob  │  │  AuditJob  │     ConcreteCreator
        │ csv|json   │  │ forces json│
        └─────┬──────┘  └─────┬──────┘
              │ new           │ new
              ▼               ▼
       ┌────────────┐  ┌────────────┐
       │ CsvReport  │  │ JsonReport │     ConcreteProduct
       └────────────┘  └────────────┘

05 — Edit freely, run it right here

Try it: the same run(), two ways of choosing the class

tsdemo.ts
type Row = Record<string, string | number>

interface Report { readonly format: string, render(rows: Row[]): string }

class CsvReport implements Report {
  readonly format = 'csv'
  render(rows: Row[]): string {
    const keys = Object.keys(rows[0] ?? {})
    return keys.join(',') + ' ; ' + rows.map(r => keys.map(k => r[k]).join(',')).join(' ; ')
  }
}

class JsonReport implements Report {
  readonly format = 'json'
  render(rows: Row[]): string { return JSON.stringify(rows) }
}

abstract class ReportJob {
  // Factory Method: every "which class" decision is funneled right here.
  abstract createReport(format: string): Report

  // Shared process: the body contains no concrete class names.
  run(query: { format: string }, rows: Row[]): string {
    const r = this.createReport(query.format)
    return '[' + r.format + '] ' + r.render(rows)
  }
}

class PublicJob extends ReportJob {
  createReport(format: string): Report {
    return format === 'json' ? new JsonReport() : new CsvReport()
  }
}

class AuditJob extends ReportJob {
  createReport(): Report { return new JsonReport() } // audit: ignores the query
}

const rows: Row[] = [{ id: 1, name: 'Mike' }, { id: 2, name: 'Ann' }]
console.log('public query=csv  -> ' + new PublicJob().run({ format: 'csv' }, rows))
console.log('public query=json -> ' + new PublicJob().run({ format: 'json' }, rows))
console.log('audit  query=csv  -> ' + new AuditJob().run({ format: 'csv' }, rows))
console
public query=csv  -> [csv] id,name ; 1,Mike ; 2,Ann
public query=json -> [json] [{"id":1,"name":"Mike"},{"id":2,"name":"Ann"}]
audit  query=csv  -> [json] [{"id":1,"name":"Mike"},{"id":2,"name":"Ann"}]

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

  • The call site knows what it needs but can't know which class to use until runtime: the format comes from a query string, the driver from env, the report type from a DB column.
  • Creating the object involves more than construction: reading config, picking a pool, wrapping with retry, choosing an encoding. A function gives those lines a proper home instead of scattering them across 12 call sites.
  • You need a test seam: pass () => fakeExporter into the service instead of letting it open a real connection.
  • You're writing the core and want other teams' plugins to register their own types without editing old code (a registry of factory functions).
  • You have a framework class with a fixed process and want to give subsystems the say over one object-creation step. Only then does the abstract-class version really have a reason to exist.
  • A class's constructor signature changes often and you don't want to grep the whole repo every time it does.

Don't use it when

  • Over-engineering. One format, one call site, and you can't name where a second type would even come from? new CsvExporter() right there is the right call. Don't write an abstract class "for later": "later" usually never comes, and the abstraction layer stays forever.
  • Don't build a whole abstract Creator hierarchy just to match the GoF diagram. In TS you trade it for this-binding bugs when methods are passed as callbacks, lost tree-shaking, and an inheritance level that carries no behavior. A plain factory function is better in the vast majority of cases.
  • Registries use string keys. registry["cvs"] compiles green and blows up at runtime. Keep a union type for the keys, as in exactly one place, and throw immediately on a miss; don't fall back to the map's first value.
  • A factory with side effects is a time bomb: a createConnection() that already opens a socket isn't idempotent; call it twice and you get two connections, test twice and you get two pools. Separate "create the object" from "connect", and give the latter its own method.
  • Factory Method doesn't remove the decision, it moves it. If after the refactor you still see if (format === ...) in three different files, you've only moved half of it; the decision is still being duplicated.

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

In real code

document.createElement(tag)

The most classic Factory Method, and you call it every day. Pass "a" and you get an HTMLAnchorElement, pass "div" and you get an HTMLDivElement; you never call new HTMLAnchorElement() in application code. One function, one string input, many returned classes, and the caller only knows the Element/HTMLElement interface.

Node: crypto.createHash, fs.createReadStream, stream.Readable.from

Node's entire object-creation API is factory functions. crypto.createHash("sha256") returns an instance of an internal class that is not exported; you can't officially new it yourself. That's why you only ever see the interface: they deliberately keep the right to change the implementation underneath.

axios.create(config) and ofetch createFetch

One "creator", and each config produces an instance with its own interceptors, baseURL and timeout. A Nuxt plugin swaps exactly this factory to attach auth headers and cookie forwarding; application code doesn't change, because it only sees the client's interface.

Nitro/Nuxt server: picking a driver from runtimeConfig at boot

You mount storage or pick a database driver based on runtimeConfig/env, not on the calling code. A test server mounts the memory driver, staging points at a read replica, prod points at the real pool: the same initialization path, with the actual class chosen in exactly one place.

08 — Try it yourself

Exercise

You have `class AuditJob` with a `private makeUploader()` method that returns `new S3Uploader("audit-prod")`. Two other places also `new S3Uploader` themselves. Refactor so that: (a) there's no `new S3Uploader` outside the factory, (b) tests run without calling S3, (c) you can add a `LocalUploader` for the dev environment without editing `AuditJob`.

Hints, open them one at a time:

  1. What's the minimal contract of an uploader? Usually just put(key, body): string.
  2. Instead of importing S3Uploader in AuditJob, accept makeUploader: () => Uploader in the constructor and default it to the real factory.
  3. To let devs register their own uploader without editing AuditJob: register it in a Record<string, () => Uploader> and read the key from env.

Extract an Uploader interface, put a createUploader() factory (reads env, returns an Uploader) in its own file, and have AuditJob take the factory via its constructor with a default value. Adding LocalUploader = a new class + one registry line. Tests pass () => ({ put: ... }) directly: no mocking library, no S3.

tsexercise.ts
interface Uploader { put(key: string, body: string): string }

class S3Uploader implements Uploader {
  constructor(private bucket: string) {}
  put(key: string) { return 's3://' + this.bucket + '/' + key }
}

class LocalUploader implements Uploader {
  put(key: string) { return 'file:///tmp/audit/' + key }
}

type UploaderFactory = () => Uploader

const registry: Record<string, UploaderFactory> = {
  s3: () => new S3Uploader('audit-prod'),
  local: () => new LocalUploader(),
}

// Read env in EXACTLY one place. A wrong key dies right at boot, which is great.
export function createUploader(kind = process.env.UPLOADER ?? 's3'): Uploader {
  const make = registry[kind]
  if (!make) throw new Error('Unknown uploader: ' + kind)
  return make()
}

export class AuditJob {
  constructor(private makeUploader: UploaderFactory = createUploader) {}
  run(key: string, body: string): string {
    return 'uploaded ' + this.makeUploader().put(key, body)
  }
}

// Test: no S3, no mocking framework.
console.log(new AuditJob(() => ({ put: k => 'memory://' + k })).run('a.log', 'x'))

09 — Read them in pairs to see the essence

Related patterns

  • Abstract FactoryFactory Method creates ONE product; Abstract Factory creates a whole FAMILY of products that must go together. A family of products is often declared as several factory methods.
  • Template MethodSame skeleton: a fixed process with one step left open for subclasses. Template Method leaves a computation step open; Factory Method leaves the object-creation step open.
  • SingletonA Creator or factory function is the natural place for a singleton: the whole system gets its connection/driver from exactly one point.
  • PrototypeInstead of `new Class` inside the factory, the factory can clone a template instance. That drops the dependency on a concrete class; change the template, change the behavior.