Skip to content
Back to Blog
Search
TypeScript / Design• 19 Oct 2026• 8 min read

Eight design patterns from my 2022 practice folder, rewritten and run

In 2022 I wrote eight design pattern exercises in PHP and TypeScript. When I came back to them, I found a factory that returned nothing for one input and a director that did not direct anything.

I rewrote all eight, type-checked them with tsc --strict (TypeScript 5.9.3), and ran them on Node.js 22.21.1. The output is from those runs. I read the old PHP without running it.

1. Singleton: one instance, but per what?

The old getInstance() cached an instance, but the public constructor still let callers create another. The rewrite makes it private:

class ConnectionPool {
  static #instance: ConnectionPool | undefined;
  static created = 0;

  private constructor() {
    ConnectionPool.created += 1;
  }

  static get(): ConnectionPool {
    ConnectionPool.#instance ??= new ConnectionPool();
    return ConnectionPool.#instance;
  }
}

const a = ConnectionPool.get();
const b = ConnectionPool.get();
console.log(a === b, "pools created:", ConnectionPool.created);
// new ConnectionPool();
// error TS2673: Constructor of class 'ConnectionPool' is private
// and only accessible within the class declaration.
true pools created: 1

TypeScript enforces private only at compile time; plain JavaScript can still call the constructor. In Node.js a cached module export often does the job. I imported it twice on the main thread and got the same object; a worker got its own:

pool module evaluated in thread 0
same object on second import: true
pool module evaluated in thread 1

Each worker or process can therefore open its own pool. Count connections across all of them.

For tests, I prefer passing the pool in: the dependency is visible and each test can use its own.

2. Factory: let the compiler find the missing case

The old factory took any. Its compiled JavaScript was stale: case 2 created a Nokia but never returned it. I ran new Factory(2) and got an error when reading show.

interface Notifier {
  send(to: string, text: string): string;
}

class EmailNotifier implements Notifier {
  send(to: string, text: string) {
    return `email to ${to}: ${text}`;
  }
}

class SmsNotifier implements Notifier {
  send(to: string, text: string) {
    return `sms to ${to}: ${text}`;
  }
}

type Channel = "email" | "sms";

function createNotifier(channel: Channel): Notifier {
  switch (channel) {
    case "email":
      return new EmailNotifier();
    case "sms":
      return new SmsNotifier();
  }
}

console.log(createNotifier("sms").send("+84 900 000 000", "order shipped"));
sms to +84 900 000 000: order shipped

Use a union and an explicit return type. Remove the SMS branch and the compiler flags the missing return:

error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

With one implementation, I would just call new EmailNotifier().

3. Abstract Factory: objects that must come in matching sets

The old PHP paired chairs and tables of the same material, but its producer returned nothing for an unknown type, so a typo would fail later as a call on null, far from its cause. The backend equivalent is a mailer and storage that must come from the same environment:

interface Mailer {
  send(to: string): string;
}
interface FileStore {
  put(key: string): string;
}
interface InfraKit {
  mailer(): Mailer;
  files(): FileStore;
}

const productionKit: InfraKit = {
  mailer: () => ({ send: (to) => `SMTP -> ${to}` }),
  files: () => ({ put: (key) => `s3://bucket/${key}` }),
};

const testKit: InfraKit = {
  mailer: () => ({ send: (to) => `captured (not sent) -> ${to}` }),
  files: () => ({ put: (key) => `memory://${key}` }),
};

function sendInvoice(kit: InfraKit, customer: string) {
  const path = kit.files().put(`invoices/${customer}.pdf`);
  const mail = kit.mailer().send(customer);
  return `${path} | ${mail}`;
}

console.log(sendInvoice(productionKit, "an@example.com"));
console.log(sendInvoice(testKit, "an@example.com"));
s3://bucket/invoices/an@example.com.pdf | SMTP -> an@example.com
memory://invoices/an@example.com.pdf | captured (not sent) -> an@example.com

Choose the kit at startup or in test setup. If those objects never vary as a pair, pass them in directly.

4. Builder: the director has to own the steps

In the old PHP, CentauBuilder calls Invoker() without new. The director also left the build steps to the caller. Here the director runs the steps itself:

class OrderQuery {
  #where: string[] = [];
  #params: unknown[] = [];
  #limit = 20;

  status(value: string) {
    this.#params.push(value);
    this.#where.push(`status = $${this.#params.length}`);
    return this;
  }

  createdAfter(date: string) {
    this.#params.push(date);
    this.#where.push(`created_at > $${this.#params.length}`);
    return this;
  }

  limit(n: number) {
    if (n < 1 || n > 100) throw new RangeError(`limit must be 1..100, got ${n}`);
    this.#limit = n;
    return this;
  }

  build() {
    const where = this.#where.length ? ` WHERE ${this.#where.join(" AND ")}` : "";
    return {
      sql: `SELECT * FROM orders${where} ORDER BY created_at DESC LIMIT ${this.#limit}`,
      params: this.#params,
    };
  }
}

// The "director": one place that knows the sequence for a recurring query.
function recentPaidOrders(since: string) {
  return new OrderQuery().status("paid").createdAfter(since).limit(50).build();
}

console.log(recentPaidOrders("2026-10-01"));

try {
  new OrderQuery().limit(500);
} catch (e) {
  console.log((e as Error).message);
}
{
  sql: 'SELECT * FROM orders WHERE status = $1 AND created_at > $2 ORDER BY created_at DESC LIMIT 50',
  params: [ 'paid', '2026-10-01' ]
}
limit must be 1..100, got 500

The builder owns placeholder numbering and validation. recentPaidOrders owns the sequence. If call order and intermediate validation do not matter, use an options object.

5. Adapter: translate amounts and errors

My old PaymentAdapter renamed send() to pay(). This one translates amounts and errors. The vendor SDK is fictional:

// The interface our code base uses everywhere.
interface PaymentGateway {
  charge(amountUsd: number, orderId: string): Promise<string>;
}

// A vendor SDK with its own shape (made up for this example).
class VendorPayClient {
  async createCharge(req: { amount_cents: number; currency: "USD"; reference: string }) {
    return { id: "ch_001", status: "succeeded", amount_cents: req.amount_cents, reference: req.reference };
  }
}

class VendorPayAdapter implements PaymentGateway {
  #client: VendorPayClient;

  constructor(client: VendorPayClient) {
    this.#client = client;
  }

  async charge(amountUsd: number, orderId: string) {
    const res = await this.#client.createCharge({
      amount_cents: Math.round(amountUsd * 100),
      currency: "USD",
      reference: orderId,
    });
    if (res.status !== "succeeded") throw new Error(`charge failed: ${res.status}`);
    return `${res.id} (${res.amount_cents} cents for ${res.reference})`;
  }
}

const gateway: PaymentGateway = new VendorPayAdapter(new VendorPayClient());
console.log(await gateway.charge(19.99, "order-42"));
ch_001 (1999 cents for order-42)

In JavaScript, 19.99 * 100 gives 1998.9999999999998. Rounding belongs at the adapter boundary in this example.

6. Decorator: wrap the same interface, mind the order

My 2022 pizza example had the right structure: each layer wrapped the same interface. Reading the code, it would print tomato pizzacheesepeper, because each layer glued its topping onto the inner string. In TypeScript the common decorators wrap functions, such as retries and timing:

type Fetch = (url: string) => Promise<string>;

function withRetry(fn: Fetch, attempts: number): Fetch {
  return async (url) => {
    for (let i = 1; ; i++) {
      try {
        return await fn(url);
      } catch (e) {
        if (i >= attempts) throw e;
        console.log(`  retry ${i} after: ${(e as Error).message}`);
      }
    }
  };
}

function withTiming(fn: Fetch): Fetch {
  return async (url) => {
    const start = performance.now();
    try {
      return await fn(url);
    } finally {
      console.log(`  ${url} took ${(performance.now() - start).toFixed(0)} ms`);
    }
  };
}

let calls = 0;
const flaky: Fetch = async (url) => {
  calls += 1;
  if (calls < 3) throw new Error("ECONNRESET");
  return `200 OK from ${url}`;
};

const fetchOrder = withTiming(withRetry(flaky, 3));
console.log(await fetchOrder("/orders/42"));
  retry 1 after: ECONNRESET
  retry 2 after: ECONNRESET
  /orders/42 took 2 ms
200 OK from /orders/42

The outer timer covers all attempts. Swap the wrappers to time each attempt separately:

  /orders/42 took 0 ms
  retry 1 after: ECONNRESET
  /orders/42 took 0 ms
  retry 2 after: ECONNRESET
  /orders/42 took 0 ms
200 OK from /orders/42

If every caller needs the same behavior, I put it in the client once.

7. Strategy: in TypeScript, often just a function

The old strategy used three classes for two stateless operations. A function type is enough here:

type Discount = (subtotal: number) => number;

const discounts: Record<string, Discount> = {
  none: () => 0,
  percent10: (subtotal) => subtotal * 0.1,
  flat5Over50: (subtotal) => (subtotal >= 50 ? 5 : 0),
};

function checkout(subtotal: number, discount: Discount) {
  return subtotal - discount(subtotal);
}

for (const [name, discount] of Object.entries(discounts)) {
  console.log(name.padEnd(12), checkout(60, discount));
}
none         60
percent10    54
flat5Over50  55

Add a discount without changing checkout. Use a class if a strategy needs state or several methods.

8. Observer: unsubscribe, and one listener can stop the rest

The first 2022 store created User1 and User2 itself, so it knew every customer by name. The second version kept a list of observers, but each observer stored the return value of a registration method that returns nothing. The folder also had the PHP Observer example from refactoring.guru, which I link instead of copying. In the rewrite, subscribe returns the function that undoes it:

type Listener<T> = (event: T) => void;

class Topic<T> {
  #listeners = new Set<Listener<T>>();

  subscribe(listener: Listener<T>) {
    this.#listeners.add(listener);
    return () => this.#listeners.delete(listener); // unsubscribe
  }

  publish(event: T) {
    for (const listener of this.#listeners) listener(event);
  }
}

type PriceChanged = { sku: string; price: number };
const priceChanged = new Topic<PriceChanged>();

priceChanged.subscribe((e) => console.log(`email: ${e.sku} now ${e.price}`));
const stopPush = priceChanged.subscribe((e) => console.log(`push: ${e.sku} now ${e.price}`));

priceChanged.publish({ sku: "PHONE-1", price: 1099 });
stopPush();
priceChanged.publish({ sku: "PHONE-1", price: 999 });
email: PHONE-1 now 1099
push: PHONE-1 now 1099
email: PHONE-1 now 999

I also checked what happens when a Node.js EventEmitter listener throws:

import { EventEmitter } from "node:events";

const orders = new EventEmitter();
orders.on("paid", () => console.log("1. reserve stock"));
orders.on("paid", () => { throw new Error("mailer is down"); });
orders.on("paid", () => console.log("3. update analytics"));

try {
  orders.emit("paid", { id: 42 });
} catch (e) {
  console.log("emit threw:", (e as Error).message);
}
1. reserve stock
emit threw: mailer is down

The third listener never ran. Both EventEmitter and the example call listeners in order, synchronously. Catch errors in each listener or use a queue if one failure must not stop the rest.

What I check now

I check what the pattern buys at the call site: a compiler error for a missing case, one place to own a sequence, or one boundary for a conversion. If I cannot point to that job, I leave the pattern out.

TypeScript / DesignRSSBack to Blog