Design Patterns in Plain Words / Module 02

Module 2: Creating Things

Factory functions, Factory Method, Builder and Singleton in TypeScript, and how Node.js module caching gives you a Singleton with no extra code.

Leo told Maya that many buyers at the spring show had asked to pay with a phone wallet. “Can we add it before the summer show?” he asked.

Maya searched the code for the line that created the card client. She found it twice, in the checkout handler and in the nightly job that retries failed payments. Each copy read its own API key from the environment.

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

Adding a wallet means changing every place that creates a payment client, and those places are hard to find. So this module is about who should create objects, and where. It teaches three ways to give object creation one home, and two more you will rarely need.

After this module, you can:

  • move object creation out of business logic into a factory function, so that a new payment provider changes one file
  • build a database query with many optional parts using a builder, and say when an options object is enough
  • share one database pool per process through Node.js module caching, and keep the code testable
  • recognize when Abstract Factory or Prototype fits, and when creating an object needs no pattern at all

The fake providers for this module

Use the folder and tsconfig.json from Module 1. TinyTickets now has two payment providers, a card provider and a wallet provider. They are fakes that print a line instead of calling a real service. Save them as providers.ts:

// Fake payment providers. They print instead of calling a real service.
export type PaymentResult =
  | { status: "paid"; chargeId: string }
  | { status: "declined"; reason: string };

export interface PaymentProvider {
  charge(amountCents: number): Promise<PaymentResult>;
}

export class CardProvider {
  constructor(apiKey: string) {
    if (apiKey === "") throw new Error("CardProvider needs an API key");
  }
  async charge(amountCents: number): Promise<PaymentResult> {
    console.log(`[card] charged ${amountCents} cents`);
    return { status: "paid", chargeId: "card_1" };
  }
}

export class WalletProvider {
  constructor(merchantId: string) {
    if (merchantId === "") throw new Error("WalletProvider needs a merchant id");
  }
  async charge(amountCents: number): Promise<PaymentResult> {
    console.log(`[wallet] charged ${amountCents} cents`);
    return { status: "paid", chargeId: "wallet_1" };
  }
}

PaymentResult is a discriminated union, as in Module 1. Its status field tells TypeScript which of the two shapes you have. Neither class says implements PaymentProvider, but both fit it, because TypeScript checks the shape, not the name (Module 1, structural typing).

Each class also needs a setting when you create it. That setting is the reason creation code spreads.

Factory function: one place that knows which class to create

Two copies of the same choice

Here is the code Maya found, cut down to the parts that matter. The buyer picks a payment method, and two functions choose and create the provider. Save it as pay-before.ts:

import { CardProvider, WalletProvider } from "./providers.ts";

type PayMethod = "card" | "wallet";

// checkout.ts: the route handler calls this
async function checkout(method: PayMethod, amountCents: number): Promise<string> {
  const provider =
    method === "card"
      ? new CardProvider(process.env.CARD_KEY ?? "test-key")
      : new WalletProvider(process.env.WALLET_ID ?? "tinytickets");
  const result = await provider.charge(amountCents);
  return result.status === "paid" ? `paid ${result.chargeId}` : `declined: ${result.reason}`;
}

// retry-payments.ts: the nightly job copies the same choice
async function retryPayment(method: PayMethod, amountCents: number): Promise<string> {
  const provider =
    method === "card"
      ? new CardProvider(process.env.CARD_KEY ?? "test-key")
      : new WalletProvider(process.env.WALLET_ID ?? "tinytickets");
  const result = await provider.charge(amountCents);
  return result.status === "paid" ? `paid ${result.chargeId}` : `still unpaid: ${result.reason}`;
}

console.log(await checkout("card", 2550));
console.log(await checkout("wallet", 2550));
console.log(await retryPayment("wallet", 1350));

Output of npx tsx pay-before.ts:

[card] charged 2550 cents
paid card_1
[wallet] charged 2550 cents
paid wallet_1
[wallet] charged 1350 cents
paid wallet_1

The code works for two methods. Then Leo asks for a third, bank transfers.

Suppose Maya adds "bank" to PayMethod and calls checkout("bank", 2550) before she edits the ternaries. tsc reports nothing, and the run prints [wallet] charged 2550 cents. The ternary sends every method that isn’t "card" to the wallet, so a bank payment reaches the wallet provider with no error.

Testing is hard too. checkout creates its own provider, so a test of a declined payment must call a real provider, or use a mocking tool that replaces the ./providers.ts import. Figure 1 shows the two copies, with the figure legend from Module 1 below them.

[checkout]       ==> [CardProvider]     reads CARD_KEY
[checkout]       ==> [WalletProvider]   reads WALLET_ID
[retryPayment]   ==> [CardProvider]     reads CARD_KEY
[retryPayment]   ==> [WalletProvider]   reads WALLET_ID

Legend, the same in every module
(Name)         a person
[name]         a module, function or class
[name] (I)     an interface: a shape that other code must fit
A --> B        A calls B
A ..> B        A implements B: A has the shape that interface B asks for
A ==> B        A creates B (with "new" or a factory function)
NEW            a part that the change added
~ await ~      the caller waits here; Node.js serves other work meanwhile

Figure 1: two functions each choose and create the provider, so a new method must be added in both.

Pause and predict: what changes when a payment method is added, and what stays the same? Where would you put the part that changes, so that checkout and retryPayment never mention a provider class? Write your answer before you read on.

Ask a factory, not the class

A factory function is a function whose job is to create an object and return it. The caller says what it wants, such as "wallet". The factory picks the class and passes the settings.

A car rental desk works the same way. You ask for “a small car”, and the desk picks one of its cars and hands you the keys. Figure 2 puts the desk next to the code.

At a car rental desk                  In TinyTickets
(Driver) asks for "a small car"       [pay-main.ts] asks for "wallet"
[rental desk]                         [createPaymentProvider]
  knows the cars, holds the keys        knows the classes, holds the keys
  ==> one car, ready to drive           ==> [WalletProvider], ready to charge

Figure 2: the caller asks for a kind of thing; the factory knows which class and which keys.

So the caller names a kind of provider, and only the factory knows the classes and their settings.

The fix: one factory, two callers that never say new

The factory goes in its own file, payment-factory.ts:

import { CardProvider, WalletProvider, type PaymentProvider } from "./providers.ts";

export type PayMethod = "card" | "wallet";
export type PayConfig = { cardKey: string; walletId: string };

// The one place that knows the classes and their settings
export function createPaymentProvider(method: PayMethod, config: PayConfig): PaymentProvider {
  switch (method) {
    case "card":
      return new CardProvider(config.cardKey);
    case "wallet":
      return new WalletProvider(config.walletId);
    default: {
      const unhandled: never = method; // compile error if a method is missing
      throw new Error(`unknown payment method: ${String(unhandled)}`);
    }
  }
}

The never line is the check from Module 1 that every case is handled. If PayMethod gains a member with no case, tsc fails. The return type is the interface PaymentProvider, so no caller learns which class it got.

checkout.ts now takes a provider and creates nothing:

import type { PaymentProvider } from "./providers.ts";

export async function checkout(provider: PaymentProvider, amountCents: number): Promise<string> {
  const result = await provider.charge(amountCents);
  return result.status === "paid" ? `paid ${result.chargeId}` : `declined: ${result.reason}`;
}

export async function retryPayment(provider: PaymentProvider, amountCents: number): Promise<string> {
  const result = await provider.charge(amountCents);
  return result.status === "paid" ? `paid ${result.chargeId}` : `still unpaid: ${result.reason}`;
}

pay-main.ts reads the settings once, and plays the part of the route handler and the nightly job:

import { checkout, retryPayment } from "./checkout.ts";
import { createPaymentProvider, type PayConfig } from "./payment-factory.ts";

// Read the settings once, when the app starts
const config: PayConfig = {
  cardKey: process.env.CARD_KEY ?? "test-key",
  walletId: process.env.WALLET_ID ?? "tinytickets",
};

console.log(await checkout(createPaymentProvider("card", config), 2550));
console.log(await checkout(createPaymentProvider("wallet", config), 2550));
console.log(await retryPayment(createPaymentProvider("wallet", config), 1350));

npx tsx pay-main.ts prints the same six lines as pay-before.ts. Figure 3 shows how the ==> arrows moved.

Before
  [checkout]      ==> [CardProvider], [WalletProvider]
  [retryPayment]  ==> [CardProvider], [WalletProvider]

After
  [pay-main.ts] --> [createPaymentProvider]                      NEW
  [createPaymentProvider] ==> [CardProvider], [WalletProvider]
  [CardProvider], [WalletProvider] ..> [PaymentProvider] (I)
  [pay-main.ts] --> [checkout], [retryPayment] --> [PaymentProvider] (I)

Figure 3: the ==> arrows to provider classes now leave one function, not two.

In the running app, the route handler does what pay-main.ts does. It asks the factory for a provider, then hands the provider to checkout.

Prove it with a test

checkout now takes any object with a charge method. So a test can pass a plain object that always declines. Save checkout.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { checkout } from "./checkout.ts";
import type { PaymentProvider } from "./providers.ts";

test("checkout reports a declined payment", async () => {
  const charged: number[] = [];
  const decliningProvider: PaymentProvider = {
    async charge(amountCents) {
      charged.push(amountCents);
      return { status: "declined", reason: "card expired" };
    },
  };

  const message = await checkout(decliningProvider, 2550);

  assert.deepEqual(charged, [2550]);
  assert.equal(message, "declined: card expired");
});

Run it with npx tsx --test checkout.test.ts:

✔ checkout reports a declined payment (0.672708ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

The old checkout could not run this test, because it created its provider inside. Those fake providers always succeed, so no test could reach the declined branch.

The next change: bank transfers

Leo’s bank-transfer request now touches one new file and one existing file. The new provider is bank-provider.ts:

import type { PaymentResult } from "./providers.ts";

// A fake bank-transfer provider. It prints instead of calling a real bank.
export class BankTransferProvider {
  constructor(accountId: string) {
    if (accountId === "") throw new Error("BankTransferProvider needs an account id");
  }
  async charge(amountCents: number): Promise<PaymentResult> {
    console.log(`[bank] transfer requested for ${amountCents} cents`);
    return { status: "paid", chargeId: "bank_1" };
  }
}

When Maya adds "bank" to PayMethod first, tsc points at the factory before any code runs:

payment-factory.ts(14,13): error TS2322: Type '"bank"' is not assignable to type 'never'.

The finished payment-factory.ts has one more import, union member, setting and case. This excerpt shows only those lines, each in its place in the file:

import { BankTransferProvider } from "./bank-provider.ts";

export type PayMethod = "card" | "wallet" | "bank";
export type PayConfig = { cardKey: string; walletId: string; bankAccountId: string };

    case "bank":
      return new BankTransferProvider(config.bankAccountId);

In pay-main.ts, the config gains bankAccountId: process.env.BANK_ACCOUNT_ID ?? "tt-main". Then a bank checkout prints:

[bank] transfer requested for 2550 cents
paid bank_1

checkout.ts and its test did not change.

Rule: When the same class choice appears in two places, move it into one factory function and let callers take the interface.

Factory Method, the class form

The fix used a function. The Factory Method is a class form of the same idea. It is one of the 23 patterns in the 1994 Gang of Four (GoF) book, Design Patterns. In this form, a base class calls a method to create an object, and each subclass overrides that method to choose the class. Save factory-method.ts:

import { CardProvider, WalletProvider, type PaymentProvider } from "./providers.ts";

abstract class PaymentJob {
  // The factory method: each subclass decides which provider to create
  protected abstract createProvider(): PaymentProvider;

  async run(amountCents: number): Promise<string> {
    const result = await this.createProvider().charge(amountCents);
    return result.status === "paid" ? `paid ${result.chargeId}` : `declined: ${result.reason}`;
  }
}

class CardPaymentJob extends PaymentJob {
  protected createProvider(): PaymentProvider {
    return new CardProvider(process.env.CARD_KEY ?? "test-key");
  }
}

class WalletPaymentJob extends PaymentJob {
  protected createProvider(): PaymentProvider {
    return new WalletProvider(process.env.WALLET_ID ?? "tinytickets");
  }
}

console.log(await new CardPaymentJob().run(2550));
console.log(await new WalletPaymentJob().run(2550));

It prints the first four lines of pay-before.ts. run is the same for every subclass, and only the created class changes. But a bank needs a new subclass, and choosing a subclass at run time still needs a switch somewhere.

Most Node.js code uses the function form, because a function that returns an object does the same job with no class tree. Use the class form when a framework’s base class already calls a create method that you must override.

Use it when, skip it when

Use a factory function when you see these signals:

  • the same if or ternary that picks a class appears in two or more places
  • business logic reads process.env to build a client
  • a test cannot run because the function under test writes new SomeClient(...)
  • creating the object takes settings that the caller should not know, such as keys or URLs

Skip it when one class is created in one place; new CardProvider(key) in the start-up file is fine. Skip it also when every object can be created once at start-up. Then an object such as Record<PayMethod, PaymentProvider>, with one provider per method, is enough. A factory is worth it when the object must be created later, for each request or job, or when the choice depends on data you only have then.

The cost

You add a file and a type for the methods (PayMethod). Your editor’s “go to definition” on provider.charge lands on the interface, so you must read the factory to learn which class runs. A stack trace from inside charge shows the provider class, but not which factory call chose it. The runtime cost is one extra function call per creation, which is small next to a network call.

Builder: a query with many optional parts

Positional parameters and a WHERE that moves

TinyTickets stores orders in PostgreSQL. Several pages list orders with different filters:

  • the organizer page, by show and status
  • the refunds report, by status
  • the admin home page, with a smaller limit

A database pool keeps a few database connections open and lends them to queries. For this module, a fake pool prints each query instead of talking to a database. Save it as db-fake.ts:

// A fake database pool. It prints instead of talking to PostgreSQL.
export type Query = { text: string; values: unknown[] };

export interface Db {
  query(q: Query): Promise<unknown[]>;
}

export class DbPool {
  static opened = 0;
  constructor(url: string) {
    DbPool.opened++;
    console.log(`[db] pool ${DbPool.opened} opened to ${url}`);
  }
  async query(q: Query): Promise<unknown[]> {
    console.log(`[db] ${q.text} ${JSON.stringify(q.values)}`);
    return [];
  }
}

Query keeps the SQL text and the values apart. $1 and $2 in the text are placeholders, slots that the database fills from values. So a buyer’s input never becomes part of the SQL. node-postgres, the common PostgreSQL client for Node.js, takes this same shape, as its query config docs show.

static opened belongs to the class, not to one object, so it counts every pool the program creates. Here is the query code, orders-before.ts:

import { DbPool, type Db, type Query } from "./db-fake.ts";

type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";

// Each new filter adds a parameter; callers pass undefined for the rest
function ordersQuery(showId?: string, status?: OrderStatus, limit = 100): Query {
  let text = "SELECT * FROM orders";
  const values: unknown[] = [];
  if (showId !== undefined) {
    values.push(showId);
    text += ` WHERE show_id = $${values.length}`;
  }
  if (status !== undefined) {
    values.push(status);
    text += values.length === 1 ? " WHERE" : " AND";
    text += ` status = $${values.length}`;
  }
  text += ` LIMIT ${limit}`;
  return { text, values };
}

const db: Db = new DbPool("postgres://localhost/tinytickets");
await db.query(ordersQuery("spring", "paid")); // the organizer page
await db.query(ordersQuery(undefined, "refunded")); // the refunds report
await db.query(ordersQuery(undefined, undefined, 20)); // the admin home page

Output:

[db] pool 1 opened to postgres://localhost/tinytickets
[db] SELECT * FROM orders WHERE show_id = $1 AND status = $2 LIMIT 100 ["spring","paid"]
[db] SELECT * FROM orders WHERE status = $1 LIMIT 100 ["refunded"]
[db] SELECT * FROM orders LIMIT 20 []

Leo’s next request is a support page that finds all orders for one buyer’s email. Maya adds buyerEmail as the first parameter and copies the showId block above the others. For Ana at the spring show, the query comes out as SELECT * FROM orders WHERE buyer_email = $1 WHERE show_id = $2 LIMIT 100. PostgreSQL rejects it, because the showId block always writes WHERE.

Three rules live in this function, and no line states them:

  • the first condition gets WHERE, and the others get AND
  • placeholders count up from $1
  • LIMIT comes last

Every new filter must follow all three by hand. And a call such as ordersQuery(undefined, undefined, 20) hides which argument is which.

Pause and predict: the filters change often, and the three rules never change. How would you write the rules once, so that each filter is one short call?

Record the choices, make the result at the end

A builder is an object that collects the parts of another object over several calls, then creates it in one build() call. Builder is one of the GoF patterns. In TypeScript, each step returns the builder, so the calls form a chain.

An order form at a print shop works the same way. You tick paper, color and number of copies, one box at a time, and nothing is printed until you hand the form in. Figure 4 lines up the form with the builder.

At a print shop                       In TinyTickets
(Customer) ticks one box              one call: .forShow("spring")
[clerk] checks the form               [OrderQueryBuilder] checks the limit
(Customer) hands the form in          .build() ==> { text, values }

Figure 4: each call records one choice; nothing is made until build().

So each call records one choice, and the query exists only after build().

The fix: OrderQueryBuilder

Save order-query.ts:

import type { Query } from "./db-fake.ts";

export type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";

export class OrderQueryBuilder {
  #conditions: string[] = [];
  #values: unknown[] = [];
  #limit = 100;

  // The rules live here once: number the placeholder, remember the value
  #where(column: string, value: unknown): this {
    this.#values.push(value);
    this.#conditions.push(`${column} = $${this.#values.length}`);
    return this;
  }

  forShow(showId: string): this {
    return this.#where("show_id", showId);
  }

  withStatus(status: OrderStatus): this {
    return this.#where("status", status);
  }

  limit(rows: number): this {
    if (!Number.isInteger(rows) || rows < 1 || rows > 500) {
      throw new Error(`limit must be 1 to 500, got ${rows}`);
    }
    this.#limit = rows;
    return this;
  }

  build(): Query {
    const where =
      this.#conditions.length > 0 ? ` WHERE ${this.#conditions.join(" AND ")}` : "";
    return { text: `SELECT * FROM orders${where} LIMIT ${this.#limit}`, values: [...this.#values] };
  }
}

A name that starts with # is a private field or private method, which code outside the class can’t use, as the MDN page on private properties explains. The return type this means each step returns the same builder, so you can chain the next call.

build() puts WHERE in front once, joins the conditions with AND, and puts LIMIT last. It copies #values, so a later change to the builder can’t change a query you already built.

The GET /orders route turns the filters it received into builder steps. Save list-orders.ts:

import type { Db } from "./db-fake.ts";
import { OrderQueryBuilder, type OrderStatus } from "./order-query.ts";

export type OrderFilters = { showId?: string; status?: OrderStatus; limit?: number };

// GET /orders: each filter the caller sent adds one step
export async function listOrders(db: Db, filters: OrderFilters): Promise<unknown[]> {
  const query = new OrderQueryBuilder();
  if (filters.showId !== undefined) query.forShow(filters.showId);
  if (filters.status !== undefined) query.withStatus(filters.status);
  if (filters.limit !== undefined) query.limit(filters.limit);
  return db.query(query.build());
}

and orders-main.ts:

import { DbPool, type Db } from "./db-fake.ts";
import { listOrders } from "./list-orders.ts";

const db: Db = new DbPool("postgres://localhost/tinytickets");
await listOrders(db, { showId: "spring", status: "paid" }); // the organizer page
await listOrders(db, { status: "refunded" }); // the refunds report
await listOrders(db, { limit: 20 }); // the admin home page

npx tsx orders-main.ts prints the same four lines as orders-before.ts. Figure 5 shows where the three rules went.

Before
  [pages] --> [ordersQuery(showId?, status?, limit?)]
                each block: push value, pick WHERE or AND, number $n

After
  [pages] --> [listOrders(db, filters)]                          NEW
  [listOrders] ==> [OrderQueryBuilder]                           NEW
  [listOrders] --> forShow, withStatus, limit, build
  [OrderQueryBuilder] #where: push value, number $n (written once)
  [OrderQueryBuilder] build: WHERE, AND, LIMIT last (written once)

Figure 5: the rules move into the builder; each filter becomes a one-line method.

Prove it with a test

The test passes a fake Db that records each query. Save list-orders.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import type { Db, Query } from "./db-fake.ts";
import { listOrders } from "./list-orders.ts";

test("listOrders sends one numbered query for two filters", async () => {
  const sent: Query[] = [];
  const fakeDb: Db = {
    async query(q) {
      sent.push(q);
      return [];
    },
  };

  await listOrders(fakeDb, { showId: "spring", status: "paid" });

  assert.deepEqual(sent, [
    {
      text: "SELECT * FROM orders WHERE show_id = $1 AND status = $2 LIMIT 100",
      values: ["spring", "paid"],
    },
  ]);
});

test("listOrders refuses a limit of 0 before it reaches the database", async () => {
  const fakeDb: Db = { query: async () => assert.fail("no query expected") };
  await assert.rejects(listOrders(fakeDb, { limit: 0 }), /limit must be 1 to 500/);
});

Output of npx tsx --test list-orders.test.ts:

✔ listOrders sends one numbered query for two filters (0.89775ms)
✔ listOrders refuses a limit of 0 before it reaches the database (0.286875ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The old ordersQuery was testable too, because it returned plain data. The difference is how much you must test. Before, each order of filters needed its own test, because each block handled WHERE and AND itself. Now the rules sit in #where and build(), so one test of two filters covers them.

The old code also never checked the limit, so it had no second test to write.

The next change: find a buyer’s orders

Leo’s support page, the change that broke the old code, now takes one method in order-query.ts and two lines in list-orders.ts. The three blocks below are excerpts of those files. The new method:

  forBuyer(email: string): this {
    return this.#where("buyer_email", email);
  }

The new field in OrderFilters:

export type OrderFilters = {
  showId?: string;
  status?: OrderStatus;
  buyerEmail?: string; // NEW
  limit?: number;
};

The new step in listOrders:

  if (filters.buyerEmail !== undefined) query.forBuyer(filters.buyerEmail); // NEW

Calling listOrders(db, { showId: "spring", buyerEmail: "ana@example.com" }) prints:

[db] SELECT * FROM orders WHERE show_id = $1 AND buyer_email = $2 LIMIT 100 ["spring","ana@example.com"]

The new method can’t put WHERE in the wrong place, because it never writes WHERE.

Rule: When every new part must follow the same rules, write the rules once in a builder, and make each part one short method.

When an options object is enough

An options object is one object whose properties are the optional settings. With it, the builder becomes one function. Save order-query-fn.ts:

import { DbPool, type Db, type Query } from "./db-fake.ts";

type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
type OrderFilters = { showId?: string; status?: OrderStatus; limit?: number };

// The function form: one options object in, one finished query out
function buildOrderQuery(filters: OrderFilters): Query {
  const conditions: string[] = [];
  const values: unknown[] = [];
  const where = (column: string, value: unknown): void => {
    values.push(value);
    conditions.push(`${column} = $${values.length}`);
  };
  if (filters.showId !== undefined) where("show_id", filters.showId);
  if (filters.status !== undefined) where("status", filters.status);
  const limit = filters.limit ?? 100;
  if (!Number.isInteger(limit) || limit < 1 || limit > 500) {
    throw new Error(`limit must be 1 to 500, got ${limit}`);
  }
  const whereText = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "";
  return { text: `SELECT * FROM orders${whereText} LIMIT ${limit}`, values };
}

const db: Db = new DbPool("postgres://localhost/tinytickets");
await db.query(buildOrderQuery({ showId: "spring", status: "paid" }));
await db.query(buildOrderQuery({ status: "refunded" }));
await db.query(buildOrderQuery({ limit: 20 }));

It prints the same four lines. It keeps the rules in one place, and a call such as { limit: 20 } names its argument. For TinyTickets’ own code, this is the simpler form to write first.

Choose the class when different functions add steps to the same query, or when a library hands you a builder.

Use it when, skip it when

Use a builder when:

  • a constructor or function has more than three or four optional parameters, and callers pass undefined to skip some
  • several pieces of code each add a part to the same object, as listOrders and a permission check might
  • the parts must follow rules, such as an order of clauses or a numbering, that every caller would otherwise repeat
  • you want one place to check the finished object before anyone uses it

Skip it when all the parts are known in one place. Then an options object with defaults does the job with no class, as in createOrder({ showId, quantity }). Skip it also for objects with two or three fields, where an object literal is enough.

The cost

A builder is a second class for each kind of object it builds. The chain hides the order of work, so a reader who sees .forShow().withStatus().build() must open the class to learn what build() does.

A builder can also be used twice by mistake. Two listOrders calls that shared one builder would add their conditions to the same list. The runtime cost is one extra object per query, and the copied values array.

Exercise: group orders

Leo wants to see group orders of four tickets or more. Add minTickets(quantity) to OrderQueryBuilder. It needs quantity >= $n, not =. What do you change in #where?

Answer

Give #where an operator parameter, and pass "=" from the existing methods. The changed lines of order-query.ts, as an excerpt:

  #where(column: string, operator: "=" | ">=", value: unknown): this {
    this.#values.push(value);
    this.#conditions.push(`${column} ${operator} $${this.#values.length}`);
    return this;
  }

  forShow(showId: string): this {
    return this.#where("show_id", "=", showId);
  }

  minTickets(quantity: number): this {
    return this.#where("quantity", ">=", quantity);
  }

new OrderQueryBuilder().forShow("spring").minTickets(4).build() returns:

{
  text: 'SELECT * FROM orders WHERE show_id = $1 AND quantity >= $2 LIMIT 100',
  values: [ 'spring', 4 ]
}

The operator type is a union of two strings, so a typo such as "=>" fails in tsc. Never pass the column name or the operator from user input, because they go into the SQL text, not into values.

Singleton and module caching: one pool for the whole process

A new pool on every call

Opening a database connection is slow, so a pool is meant to live as long as the app. The node-postgres pooling guide explains why. Here is how two TinyTickets helpers used the pool, singleton-before.ts:

import { DbPool } from "./db-fake.ts";

const url = process.env.DATABASE_URL ?? "postgres://localhost/tinytickets";

// shows.ts
async function findShow(showId: string): Promise<unknown[]> {
  const db = new DbPool(url);
  return db.query({ text: "SELECT * FROM shows WHERE id = $1", values: [showId] });
}

// orders.ts
async function findOrders(showId: string): Promise<unknown[]> {
  const db = new DbPool(url);
  return db.query({ text: "SELECT * FROM orders WHERE show_id = $1", values: [showId] });
}

// show-page.ts: two buyers open the show page
for (const buyer of ["Ana", "Ben"]) {
  console.log(`page for ${buyer}`);
  await findShow("spring");
  await findOrders("spring");
}

Output:

page for Ana
[db] pool 1 opened to postgres://localhost/tinytickets
[db] SELECT * FROM shows WHERE id = $1 ["spring"]
[db] pool 2 opened to postgres://localhost/tinytickets
[db] SELECT * FROM orders WHERE show_id = $1 ["spring"]
page for Ben
[db] pool 3 opened to postgres://localhost/tinytickets
[db] SELECT * FROM shows WHERE id = $1 ["spring"]
[db] pool 4 opened to postgres://localhost/tinytickets
[db] SELECT * FROM orders WHERE show_id = $1 ["spring"]

Two page views opened four pools. On a sale day, many buyers arrive in the same minute, and every request opens new connections. PostgreSQL allows typically 100 connections by default, as its documentation on max_connections says, and requests fail once they run out.

The pools are also never closed. And the helpers have the testing trap from Module 1, because a test of findOrders opens a real pool.

Pause and predict: how many pools should this process have? Where should the line that creates it live, and how do findShow and findOrders reach it?

One shared object, created in one place

A Singleton is a class that has only one instance and gives every caller one global way to reach it. Singleton is one of the GoF patterns. In Node.js, a module file already gives you the first half. Module 1 showed that a file’s top-level code runs once, and every import of the file gets the same objects.

The second half, a global way in, is the part that makes testing hard. So the fix below keeps it small.

Think of the printer by the office door. Everyone sends pages to that one printer, and nobody buys a printer to print one page. Figure 6 places the office next to the code.

In an office                          In TinyTickets
[the printer by the door]             [db.ts] exports pool
desk 1 --> the printer                [show-page.ts] --> pool
desk 2 --> the printer                [report.ts] --> pool
nobody buys a printer per page        nobody writes new DbPool per query

Figure 6: every file uses one shared object; nobody creates one per use.

So every file uses the one pool that db.ts creates, and no code creates a pool per query.

The fix: db.ts creates the pool, the helpers take it

The pool moves into a small file of its own, db.ts:

import { DbPool } from "./db-fake.ts";

// Runs once, the first time any file imports db.ts
export const pool = new DbPool(process.env.DATABASE_URL ?? "postgres://localhost/tinytickets");

The helpers stop creating anything. They take a Db, the interface from db-fake.ts, as their first parameter. Save queries.ts:

import type { Db } from "./db-fake.ts";

export async function findShow(db: Db, showId: string): Promise<unknown[]> {
  return db.query({ text: "SELECT * FROM shows WHERE id = $1", values: [showId] });
}

export async function findOrders(db: Db, showId: string): Promise<unknown[]> {
  return db.query({ text: "SELECT * FROM orders WHERE show_id = $1", values: [showId] });
}

and show-page.ts:

import { pool } from "./db.ts";
import { findOrders, findShow } from "./queries.ts";

// The route file is the only place that imports the pool
for (const buyer of ["Ana", "Ben"]) {
  console.log(`page for ${buyer}`);
  await findShow(pool, "spring");
  await findOrders(pool, "spring");
}

Pause and predict: how many [db] pool lines does this print, and does the first one come before or after page for Ana?

Output of npx tsx show-page.ts:

[db] pool 1 opened to postgres://localhost/tinytickets
page for Ana
[db] SELECT * FROM shows WHERE id = $1 ["spring"]
[db] SELECT * FROM orders WHERE show_id = $1 ["spring"]
page for Ben
[db] SELECT * FROM shows WHERE id = $1 ["spring"]
[db] SELECT * FROM orders WHERE show_id = $1 ["spring"]

The four queries are the same as before, but one pool opens instead of four. It opens before page for Ana, because Node.js ran db.ts while it loaded the imports of show-page.ts. Node.js then keeps each loaded file in its module cache, so any later import of db.ts gets the same pool and runs nothing again.

Rule: Node.js runs the files a module imports before the first line of the module itself.

Two decisions sit in this fix. db.ts makes sure there is one pool, which is the Singleton’s job. The helpers take the pool as a parameter, so only the route file uses the global way in. Figure 7 shows the arrows.

Before
  [findShow]   ==> [DbPool]    on every call
  [findOrders] ==> [DbPool]    on every call

After
  [db.ts] ==> [DbPool]    once, on first import                  NEW
  [show-page.ts] --> [db.ts]  imports pool
  [show-page.ts] --> [findShow], [findOrders] --> [Db] (I)
  [DbPool] ..> [Db] (I)
  [queries.test.ts] ==> [fakeDb] ..> [Db] (I)                    NEW

Figure 7: one file creates the pool; the helpers depend on the Db shape, not on db.ts.

Prove it with a test

findOrders takes any object with a query method. Save queries.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import type { Db, Query } from "./db-fake.ts";
import { findOrders } from "./queries.ts";

test("findOrders asks for one show's orders", async () => {
  const sent: Query[] = [];
  const fakeDb: Db = {
    async query(q) {
      sent.push(q);
      return [{ id: "o1" }];
    },
  };

  const rows = await findOrders(fakeDb, "spring");

  assert.equal(rows.length, 1);
  assert.deepEqual(sent, [{ text: "SELECT * FROM orders WHERE show_id = $1", values: ["spring"] }]);
});

Output of npx tsx --test queries.test.ts:

✔ findOrders asks for one show's orders (0.728417ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

The test never imports db.ts, so no pool opens. With the old code, the test would open a real pool, or need a mocking tool that replaces DbPool inside the module.

The next change: a second database for reports

Leo’s nightly sales report is slow, so Maya wants it to read from a read-only copy of the database. With the module form, db.ts gains one export. This excerpt shows it below the existing pool:

// NEW: a read-only copy of the database for slow reports
export const reportPool = new DbPool(process.env.REPORT_DATABASE_URL ?? "postgres://replica/tinytickets");

The report passes reportPool to the same findOrders. Save report.ts:

import { reportPool } from "./db.ts";
import { findOrders } from "./queries.ts";

// NEW: the nightly sales report reads from the copy
const rows = await findOrders(reportPool, "spring");
console.log(`report: ${rows.length} orders`);

Output:

[db] pool 1 opened to postgres://localhost/tinytickets
[db] pool 2 opened to postgres://replica/tinytickets
[db] SELECT * FROM orders WHERE show_id = $1 ["spring"]
report: 0 orders

queries.ts and its test did not change. But the output shows a cost. Importing db.ts opens both pools, even though the report uses one, and the lazy form below fixes that.

The class form and the lazy form

Most pattern books show a class form. Save database-class.ts:

import { DbPool } from "./db-fake.ts";

// The GoF class form, as Java-style code writes it
export class Database {
  static #instance: Database | undefined;
  readonly pool: DbPool;

  private constructor() {
    this.pool = new DbPool(process.env.DATABASE_URL ?? "postgres://localhost/tinytickets");
  }

  static getInstance(): Database {
    Database.#instance ??= new Database();
    return Database.#instance;
  }
}

const first = Database.getInstance();
const second = Database.getInstance();
console.log("same object:", first === second);

Output:

[db] pool 1 opened to postgres://localhost/tinytickets
same object: true

A private constructor can be called only from code inside the class; anywhere else, new Database() fails in tsc with error TS2673. The ??= operator assigns only when the left side is null or undefined. So the first call creates the instance, and later calls reuse it.

Prefer the module form in TypeScript. The module cache already makes one instance, so getInstance enforces nothing new. It also blocks the report change, because getInstance() can only ever return one pool. And a helper that calls Database.getInstance() inside has the Module 1 trap, because no test can hand it a fake.

A lazy instance is created on its first use instead of on import. A function and a variable outside it are enough for that. Save lazy-db.ts:

import { DbPool } from "./db-fake.ts";

let pool: DbPool | undefined;

// Created on the first call, not on import
export function getPool(): DbPool {
  pool ??= new DbPool(process.env.DATABASE_URL ?? "postgres://localhost/tinytickets");
  return pool;
}

console.log("imported, no pool yet");
console.log("same object:", getPool() === getPool());

Output:

imported, no pool yet
[db] pool 1 opened to postgres://localhost/tinytickets
same object: true

Use the lazy form when importing the file must stay cheap. One example is a command-line script that often exits before it needs the database.

One instance per process

“One instance” means one per loaded copy of db.ts, and each Node.js process loads its own copy. So if you run four copies of the app, you have four pools, and four times the connections. A worker thread, a second JavaScript thread inside the same process, also loads db.ts again and gets its own pool. “Going deeper” at the end of this module shows the worker case and two more.

Use it when, skip it when

Use one module-level instance when:

  • the object holds something expensive and long-lived, such as a database pool, an HTTP client with open connections, or a cache
  • creating it twice would be a bug, such as two pools that together go over the connection limit
  • the object has no data that belongs to one request or one buyer

Skip it for anything that belongs to one request, one buyer or one show; create those per call and pass them along. Skip the class form with getInstance in TypeScript, because an exported const or a getPool() function does the same job. Skip it also when the shared object is cheap to create and holds no connections, such as a price formatter.

The cost

A module-level instance is a global value with a file name. Any file can import it, and nothing tells you which ones do.

The object is created at import time, so a file that only wants a type can open a pool by accident if it imports db.ts. The instance lives as long as the process, so you must close it on shutdown yourself. Tests need care too, so pass the object as a parameter, as queries.ts does.

Exercise: which objects should be one per process?

TinyTickets creates these four objects. Which ones should be a single module-level instance, and which should be created per call?

  1. the database pool
  2. an Order object for Ana’s checkout
  3. the MailClient, which keeps a connection to the mail server open
  4. a logger that adds the current request id to each line
Answer

One per process: 1 and 3. Both hold connections that are slow to open and that a server limits.

Per call: 2 and 4. An order is data for one buyer. The logger holds a request id, so a shared one would mix up lines from two requests. A common shape is one shared base logger, plus a small object per request that adds the id.

Two creational patterns you will rarely need

Abstract Factory: a matching set of objects

In TinyTickets, an organizer may try the site in sandbox mode, where nothing real happens. Sandbox payments must pair with sandbox messages. A live payment must never pair with a sandbox message.

An Abstract Factory is a GoF pattern that creates a family of related objects that must be used together. You call one factory, and every object it returns belongs to the same family. Figure 8 shows one function per mode, each returning a matching kit.

[pay-main.ts] --> [createKit(mode)]
  "live"    ==> { pay: [CardProvider],      send: [MailClient sender] }
  "sandbox" ==> { pay: [FakePayProvider],   send: [log-only sender] }
both kits ..> [Kit] (I) = { pay: PaymentProvider; send: Send }

Figure 8: one call returns the whole kit, so payments and messages always come from the same mode.

You need it when two or more kinds of objects vary together, and mixing them would be a bug. In TypeScript, a function that returns an object of the right shape is the usual form. The cost is one more interface, Kit, that every mode must fill.

Prototype: copy a configured object

Leo repeats “Summer Lights” a week later, so the encore is a copy with a new id and date. Prototype is a GoF pattern that creates a new object by copying an existing one and then changing a few fields. It helps when an object takes many settings and you need several that differ slightly. Save prototype.ts:

type Show = { id: string; title: string; date: string; priceCents: number };

const summer: Show = { id: "summer", title: "Summer Lights", date: "2027-06-20", priceCents: 1500 };

// Spread copies one level: enough for a flat object like Show
const encore: Show = { ...summer, id: "summer-2", date: "2027-06-27" };

// structuredClone copies every level, so nested arrays are not shared
const template = { show: summer, heldSeats: ["A1", "A2"] };
const copy = structuredClone(template);
copy.heldSeats.push("A3");

console.log(encore.title, encore.date);
console.log(template.heldSeats.length, copy.heldSeats.length);

Output:

Summer Lights 2027-06-27
2 3

The spread syntax { ...summer } copies the top level only. structuredClone, built into Node.js, copies every level, so the template’s seat list stays at two.

You need it when you build an object with many settings, then build a near-copy of it by hand. The cost is the shallow copy, because a spread copy shares nested arrays and objects with the original.

A decision figure for creation code

Figure 9 starts from the creation code in front of you and asks one question at each step.

You see new X(...) or a long creation call
  |
  v
Is it in business logic, and does it block a test or     -- no --> No pattern
repeat a class choice?                                              needed.
  | yes
  v
Does the caller pick one of several classes?   -- yes --> Factory function
  | no                                         (object map if all are made
  v                                           once at start-up)
Many optional parts, added in steps by        -- yes --> Builder
different code?                               (one caller: options object)
  | no
  v
Must one object serve the whole process?      -- yes --> Export one
  | no                                        instance from a module; pass
  v                                           it in as a parameter
Create it where it is used, or pass it in (Module 6)

Figure 9: most creation code leaves at the first exit; a pattern answers one specific question.

Check yourself

  1. After the factory fix, which files change when a “bank” payment method arrives, and how does tsc point you to the missing case?
  2. In one sentence, how is a factory function different from the GoF Factory Method?
  3. When is an options object enough, so that you do not need a builder?
  4. Why does export const pool = new DbPool(...) in db.ts give one pool, and what is one case that gives a second pool?
  5. Name the pattern: (a) you need a copy of a configured show with a new date; (b) sandbox payments must always pair with sandbox messages.
Answers
  1. A new provider file and payment-factory.ts (the union, the setting and one case), plus the setting in the start-up file. Callers do not change. When "bank" is in PayMethod but has no case, the never line fails with TS2322.
  2. A factory function is a plain function that picks and creates an object; Factory Method is a method in a base class that each subclass overrides to choose the class.
  3. When one caller knows all the parts at one moment, and no other code adds parts later.
  4. Node.js runs db.ts once and keeps it in the module cache, so every import gets the same pool. A second process, or a worker thread in the same process, gets a second pool.
  5. (a) Prototype, with spread or structuredClone. (b) Abstract Factory, as one function per mode that returns a matching kit.

Lab: a seat-map client that works without a network

Time: about 20 minutes. Use a new folder with the tsconfig.json from Module 1.

TinyTickets asks the slow seat-map service which seats are free. Here is the fake client, seat-map-fake.ts. It prints instead of calling the network:

// A fake client for the seat-map service. It prints instead of calling the network.
export class SeatMapHttpClient {
  constructor(baseUrl: string) {
    console.log(`[seats] client created for ${baseUrl}`);
  }
  async getSeatMap(showId: string, signal: AbortSignal): Promise<string[]> {
    signal.throwIfAborted();
    console.log(`[seats] GET /shows/${showId}/seats`);
    return ["A1", "A2", "B7"];
  }
}

signal.throwIfAborted() throws if the signal has already fired, so a call whose time limit has passed does no work. Here is the code that uses it, seats.ts:

import { SeatMapHttpClient } from "./seat-map-fake.ts";

export async function seatsLeft(showId: string): Promise<number> {
  const client = new SeatMapHttpClient("https://seats.tinytickets.example");
  const seats = await client.getSeatMap(showId, AbortSignal.timeout(2000));
  return seats.length;
}

export async function isSeatFree(showId: string, seat: string): Promise<boolean> {
  const client = new SeatMapHttpClient("https://seats.tinytickets.example");
  const seats = await client.getSeatMap(showId, AbortSignal.timeout(2000));
  return seats.includes(seat);
}

and run-seats.ts:

import { isSeatFree, seatsLeft } from "./seats.ts";

console.log(`${await seatsLeft("spring")} seats left`);
console.log(`B7 free: ${await isSeatFree("spring", "B7")}`);

Output today:

[seats] client created for https://seats.tinytickets.example
[seats] GET /shows/spring/seats
3 seats left
[seats] client created for https://seats.tinytickets.example
[seats] GET /shows/spring/seats
B7 free: true

The change request has two parts. First, Maya wants to work on a train with no network. When the environment variable SEATS_MODE is local, TinyTickets must use a built-in seat map with seats A1, A2 and A3, and never call the service.

Second, the app must create the seat-map client once, not on every call.

Refactor the code so that this test file, seats.test.ts, passes:

import { test } from "node:test";
import assert from "node:assert/strict";
import { createSeatMapClient, type SeatMapClient } from "./seat-map.ts";
import { isSeatFree, seatsLeft } from "./seats.ts";

const fakeClient: SeatMapClient = {
  async getSeatMap(showId, signal) {
    assert.equal(signal.aborted, false);
    return showId === "spring" ? ["A1", "B7"] : [];
  },
};

test("seatsLeft counts the seats from the client it is given", async () => {
  assert.equal(await seatsLeft(fakeClient, "spring"), 2);
});

test("isSeatFree checks one seat", async () => {
  assert.equal(await isSeatFree(fakeClient, "spring", "B7"), true);
  assert.equal(await isSeatFree(fakeClient, "spring", "C1"), false);
});

test("local mode answers without the seat-map service", async () => {
  const client = createSeatMapClient({ mode: "local" });
  const seats = await client.getSeatMap("spring", AbortSignal.timeout(100));
  assert.deepEqual(seats, ["A1", "A2", "A3"]);
});

Run it with npx tsx --test seats.test.ts, and check types with npx tsc --noEmit. Then update run-seats.ts so that npx tsx run-seats.ts creates the client once, and SEATS_MODE=local npx tsx run-seats.ts never prints a [seats] line.

Pause and predict: which of this module’s patterns does each part of the change request need? Which file should hold the one shared client?

Hint 1

The test names three things you must write: an interface SeatMapClient, a factory createSeatMapClient, and new signatures for seatsLeft and isSeatFree. Both functions take the client as their first parameter, as findOrders took the Db.

Hint 2

Make the factory’s settings a discriminated union: type SeatMapConfig = { mode: "local" } | { mode: "http"; baseUrl: string }. A local client can be a plain object with a getSeatMap method; it fits the interface without a class.

Hint 3

Do not create the shared client in seat-map.ts, because the test imports that file and would create it too. Put it in a small file of its own, the way db.ts holds the pool, and import it only from run-seats.ts.

Solution

seat-map.ts, the interface and the factory:

import { SeatMapHttpClient } from "./seat-map-fake.ts";

export interface SeatMapClient {
  getSeatMap(showId: string, signal: AbortSignal): Promise<string[]>;
}

export type SeatMapConfig = { mode: "local" } | { mode: "http"; baseUrl: string };

// The factory: the one place that knows which client to make
export function createSeatMapClient(config: SeatMapConfig): SeatMapClient {
  if (config.mode === "local") {
    return {
      async getSeatMap(_showId, signal) {
        signal.throwIfAborted();
        return ["A1", "A2", "A3"];
      },
    };
  }
  return new SeatMapHttpClient(config.baseUrl);
}

seat-map-client.ts, the one shared instance:

import { createSeatMapClient } from "./seat-map.ts";

// The one shared client, created the first time this file is imported
export const seatMapClient = createSeatMapClient(
  process.env.SEATS_MODE === "local"
    ? { mode: "local" }
    : { mode: "http", baseUrl: "https://seats.tinytickets.example" },
);

seats.ts, which creates nothing:

import type { SeatMapClient } from "./seat-map.ts";

export async function seatsLeft(client: SeatMapClient, showId: string): Promise<number> {
  const seats = await client.getSeatMap(showId, AbortSignal.timeout(2000));
  return seats.length;
}

export async function isSeatFree(client: SeatMapClient, showId: string, seat: string): Promise<boolean> {
  const seats = await client.getSeatMap(showId, AbortSignal.timeout(2000));
  return seats.includes(seat);
}

run-seats.ts:

import { seatMapClient } from "./seat-map-client.ts";
import { isSeatFree, seatsLeft } from "./seats.ts";

console.log(`${await seatsLeft(seatMapClient, "spring")} seats left`);
console.log(`B7 free: ${await isSeatFree(seatMapClient, "spring", "B7")}`);

Output of npx tsx run-seats.ts:

[seats] client created for https://seats.tinytickets.example
[seats] GET /shows/spring/seats
3 seats left
[seats] GET /shows/spring/seats
B7 free: true

Output of SEATS_MODE=local npx tsx run-seats.ts:

3 seats left
B7 free: false

The test passes with ℹ pass 3 and ℹ fail 0, and the old files fail it.

You used two patterns. The factory createSeatMapClient is the one place that knows the two kinds of client. seat-map-client.ts creates one client for the process through module caching, and only run-seats.ts imports it. The seat functions depend on the SeatMapClient shape, so the test fills it with a plain object.

The 2-second timeout is still written twice in seats.ts. That’s a separate change, and Module 9 wraps remote calls with timeouts and retries in one place.

Which pattern, if any?

Scenario 1: a new field on an order

Here is how TinyTickets creates an order, create-order-before.ts:

type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
interface Order {
  id: string;
  showId: string;
  buyerEmail: string;
  quantity: number;
  totalCents: number;
  status: OrderStatus;
}

function createOrder(id: string, showId: string, buyerEmail: string, quantity: number, priceCents: number): Order {
  const fee = quantity >= 4 ? 0 : 150;
  return { id, showId, buyerEmail, quantity, totalCents: priceCents * quantity + fee, status: "pending" };
}

console.log(createOrder("o1", "spring", "ana@example.com", 2, 1200));

It prints an order with totalCents: 2550 and status: 'pending'. The new requirement is that the box office sells tickets for cash at the door, so those orders start as "paid". A teammate proposes an OrderBuilder class with withStatus, withQuantity and the other fields. Which pattern, if any, would you use?

Hint 1

Ask the builder questions from Figure 9. Is the order made in steps by different code, or in one call? Are there rules for combining the parts?

Hint 2

The real problem is five positional parameters, and a sixth would make it worse. Which simpler tool from the builder section fixes that?

Strong answer

No pattern. Every field is known at one moment, in one call, and the one rule (the booking fee) already lives in the function. A builder would add a class and a chain for nothing. Change the parameters to an options object with a default status, create-order-after.ts:

type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
interface Order {
  id: string;
  showId: string;
  buyerEmail: string;
  quantity: number;
  totalCents: number;
  status: OrderStatus;
}
type NewOrder = {
  id: string;
  showId: string;
  buyerEmail: string;
  quantity: number;
  priceCents: number;
  status?: OrderStatus;
};

function createOrder(o: NewOrder): Order {
  const fee = o.quantity >= 4 ? 0 : 150;
  const totalCents = o.priceCents * o.quantity + fee;
  return { id: o.id, showId: o.showId, buyerEmail: o.buyerEmail, quantity: o.quantity, totalCents, status: o.status ?? "pending" };
}

console.log(createOrder({ id: "o1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, priceCents: 1200 }));
console.log(createOrder({ id: "o2", showId: "spring", buyerEmail: "ben@example.com", quantity: 4, priceCents: 1200, status: "paid" }));

The first order prints as before. The second is Ben’s box-office order, with totalCents: 4800, no booking fee for four tickets, and status: 'paid'. Each call now names its arguments, so nobody can swap quantity and priceCents by accident.

Scenario 2: CSV files of shows from new organizers

The nightly show import reads CSV files of shows from organizers. Here is the line parser, import-before.ts:

type ShowRow = { title: string; date: string };

// Each organizer's file looks different
function parseLine(organizer: string, line: string): ShowRow | null {
  if (organizer === "leo") {
    const [title, date] = line.split(",");
    return title && date ? { title, date } : null;
  } else if (organizer === "club-north") {
    const [title, day] = line.split(";"); // dates arrive as 14.03.2027
    const [d, m, y] = (day ?? "").split(".");
    return title && d && m && y ? { title, date: `${y}-${m}-${d}` } : null;
  }
  throw new Error(`no parser for ${organizer}`);
}

console.log(parseLine("leo", "Songs of Spring,2027-03-14"));
console.log(parseLine("club-north", "Summer Lights;20.06.2027"));

Output:

{ title: 'Songs of Spring', date: '2027-03-14' }
{ title: 'Summer Lights', date: '2027-06-20' }

The new requirement is a third organizer, “hall-south”, who sends tab-separated files with dates like 2027-03-21. Leo expects more organizers this year, and some will send the same format as an existing one. Which pattern, if any, would you use?

Hint 1

List what changes and what stays the same. The organizers change. The formats change less often. The steps (split the line, read the title, turn the date into YYYY-MM-DD) stay the same.

Hint 2

Two organizers with the same format should not need two branches. Try letting each organizer point to a format, with one function that turns a format’s settings into a parser.

Strong answer

A factory function, fed by two object maps. One map gives each format its settings, and one map gives each organizer its format. createLineParser turns settings into a parser function, the closure form from Module 1. import-after.ts:

type ShowRow = { title: string; date: string };
type ParseLine = (line: string) => ShowRow | null;
type FileFormat = { separator: string; dayFirst: boolean };
type FormatName = "comma" | "semicolon" | "tab";

// What changes: one entry per format. Organizers point to a format.
const formats: Record<FormatName, FileFormat> = {
  comma: { separator: ",", dayFirst: false },
  semicolon: { separator: ";", dayFirst: true },
  tab: { separator: "\t", dayFirst: false }, // NEW
};

const organizerFormat: Record<string, FormatName> = {
  leo: "comma",
  "club-north": "semicolon",
  "hall-south": "tab", // NEW
};

// A factory function: settings in, a parser out
function createLineParser({ separator, dayFirst }: FileFormat): ParseLine {
  return (line) => {
    const [title, day] = line.split(separator);
    if (!title || !day) return null;
    if (!dayFirst) return { title, date: day };
    const [d, m, y] = day.split(".");
    return d && m && y ? { title, date: `${y}-${m}-${d}` } : null;
  };
}

function parserFor(organizer: string): ParseLine {
  const format = organizerFormat[organizer];
  if (format === undefined) throw new Error(`no format for ${organizer}`);
  return createLineParser(formats[format]);
}

console.log(parserFor("leo")("Songs of Spring,2027-03-14"));
console.log(parserFor("club-north")("Summer Lights;20.06.2027"));
console.log(parserFor("hall-south")("Songs of Spring\t2027-03-21"));

Output:

{ title: 'Songs of Spring', date: '2027-03-14' }
{ title: 'Summer Lights', date: '2027-06-20' }
{ title: 'Songs of Spring', date: '2027-03-21' }

The first two lines match the old output. A new organizer with a known format is one line in organizerFormat, and a new format is one entry in formats. You call parserFor once per file, not once per line.

It needs no builder, because a format has two fields. It needs no class either, because the parser keeps no state. In a real import, organizerFormat would come from the database, not from code.

Get feedback on your answer

Copy this prompt into an AI assistant, and paste your answer where it says so:

I am learning design patterns in TypeScript and Node.js. Here is a
scenario, the code, and my answer. Review my answer as a senior Node.js
developer would. Say whether a pattern is needed at all, whether a
simpler option (a plain function, an options object, an object map)
would do, and what my answer costs in files and indirection. Do not
rewrite everything; point to the two most important changes.

Scenario: [paste the scenario and its code]
My answer: [paste your answer and your code]

Going deeper

You can skip this section. It covers details the main path left out.

More ways to get a second instance

A module-level instance is one per loaded copy of its file. Besides a second process, four cases give you another copy:

  • A worker thread. It loads db.ts again, as the script below shows. Workers come from node:worker_threads.
  • A different spelling of the path. Node.js caches ES modules by their resolved URL, as the ES modules docs say. On a case-insensitive file system, such as the macOS default, import("./DB.ts") and import("./db.ts") load the same file twice. tsc catches this with error TS1149, because its forceConsistentCasingInFileNames check is on by default.
  • Two copies of a package. Two different node_modules folders each hold their own copy, as Module 1 showed.
  • Test files. The Node.js test runner runs each test file in its own child process by default. So a module-level object is fresh in each test file, but shared by every test inside one file.

Save worker.ts to see the worker case:

import { Worker, isMainThread } from "node:worker_threads";
import { pool } from "./db.ts";

if (isMainThread) {
  new Worker(new URL(import.meta.url));
}
console.log(isMainThread ? "main thread" : "worker thread", "has a pool:", pool !== undefined);

Output of npx tsx worker.ts:

[db] pool 1 opened to postgres://localhost/tinytickets
main thread has a pool: true
[db] pool 1 opened to postgres://localhost/tinytickets
worker thread has a pool: true

The worker printed pool 1 again. Even the static counter DbPool.opened starts over in the worker, because the worker loaded db-fake.ts again too.

The Builder’s director

The GoF version of Builder also has a “director” object that runs the steps, so that one set of steps can produce different results. The form you meet in TypeScript code leaves it out.

Seen in the wild

  • Node.js crypto.createHash(algorithm) is a factory function. You pass a name such as "sha256", and it returns a Hash object.
  • NestJS is a Node.js framework that creates your classes and passes in what they need. Its factory providers (useFactory) register a function whose return value becomes the provider. Module 6 shows NestJS in full.
  • Knex.js calls itself a SQL query builder. You chain calls such as where and limit, and Knex writes the SQL.
  • TypeORM maps database tables to TypeScript classes. Its createQueryBuilder returns a builder with where, andWhere and getOne, and Module 7 comes back to it.
  • Node.js http.globalAgent is one shared Agent object that every HTTP client request uses, unless you pass another one.
  • NestJS providers have singleton scope by default, so one instance is shared across the whole application. The framework passes it in, so your class never calls getInstance.

Names that sound alike

  • Strategy (Module 4). The factory chooses and creates an object; a strategy is the object that does the varying work. So createPaymentProvider creates a strategy.
  • Dependency Injection (Module 6). It decides who calls the factory and passes the result in. A DI container’s “singleton” scope makes one instance and passes it in, so no code reaches for it globally.
  • Method chaining. Express’s res.status(404).json(...) chains because res.status returns res, but it sends a response at once. A chain is a builder only when the object is made at the end.

Cheat sheet

Pattern The problem it solves The signal in your code
Factory function A class choice is copied, or blocks a test The same if or ternary around new in two places
Factory Method A base class needs an object its subclasses choose A framework class asks you to override a create... method
Builder Many optional parts with rules for combining them Calls such as f(undefined, undefined, 20), or SQL glued with WHERE and AND
Singleton (module instance) An expensive object is created again and again new DbPool(...) inside a helper; a getInstance() method
Abstract Factory A family of objects must match Two if (mode === ...) choices that must always agree
Prototype Near-copies of a configured object An object built by hand, then built again with one field changed
No pattern Creation happens once, in one place One new in the start-up file, or a small object literal
  • Factory function: one function picks the class and passes the settings, so a new provider changes one file, and callers take the interface.
  • Builder: each step records one part, and build() applies the rules once. When one caller knows every part, an options object is enough.
  • Singleton: export one instance from a module, and pass it to helpers as a parameter, so a test can hand in a fake.
  • One per process: a second process or a worker thread gets its own instance.
  • First question: is a pattern needed at all? Creation that happens once, in one place, needs none (Figure 9).

Next, Module 3 takes objects you already have, such as a provider SDK whose methods do not fit PaymentProvider, and wraps them with Adapter, Facade, Decorator and Proxy.

Sources