Skip to the content

Lesson 269 of 296

Design patterns: factory, strategy and observer

What you will learn

  • What design patterns are
  • The factory pattern
  • The strategy pattern
  • The observer pattern (and events)
  • How these appear in everyday JavaScript
On this page

What are design patterns?

Design patterns are well-known, named solutions to common design problems, popularised by the 1994 "Gang of Four" book. Knowing the names lets developers communicate quickly ("let's use a strategy here"). In TypeScript many patterns are simpler than in classic Java, because functions are values. Use a pattern when it solves a real problem, not to show off.

Factory

Problem: creating objects involves choosing a type or doing setup that callers should not repeat or know about.
Solution: a factory function or method that creates and returns the right object.

TypeScript
export interface Notifier {
  readonly channel: string;
  send(to: string, message: string): Promise<string>;
}

class EmailNotifier implements Notifier {
  readonly channel = "email";
  async send(to: string, message: string) {
    return `email to ${to}: ${message}`;
  }
}

class SmsNotifier implements Notifier {
  readonly channel = "sms";
  async send(to: string, message: string) {
    return `sms to ${to}: ${message.slice(0, 160)}`;
  }
}

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

Callers ask for "a notifier for email" and receive something that implements Notifier; they never use new SmsNotifier() directly. Real examples: createRoot() in React, express(), DynamoDBDocumentClient.from(...), Nest's useFactory providers (Lesson 208).

Strategy

Problem: an algorithm needs to vary (pricing, shipping, sorting, validation), and a growing if/switch makes the code hard to extend (Open/Closed, Lesson 267).
Solution: define a family of interchangeable strategies with the same interface and pick one at runtime.

TypeScript
export type ShippingStrategy = {
  name: string;
  costPence(weightKg: number, subtotalPence: number): number;
};

export const standardShipping: ShippingStrategy = {
  name: "standard",
  costPence: (_weightKg, subtotalPence) => (subtotalPence >= 5000 ? 0 : 399)
};

export const expressShipping: ShippingStrategy = {
  name: "express",
  costPence: (weightKg) => 799 + Math.ceil(weightKg) * 50
};

export const collectInStore: ShippingStrategy = {
  name: "collect",
  costPence: () => 0
};

export function checkoutTotal(subtotalPence: number, weightKg: number, shipping: ShippingStrategy): number {
  return subtotalPence + shipping.costPence(weightKg, subtotalPence);
}

Adding "next day delivery" means adding one object; checkoutTotal does not change. In JavaScript a strategy is often just a function passed as an argument: the comparator passed to Array.prototype.sort is a strategy.

Observer

Problem: when something happens in one object, several others need to react, and the source should not know about all of them.
Solution: subscribers register with a subject (publisher); the subject notifies all of them when an event occurs.

TypeScript
type Listener<T> = (payload: T) => void;

export class EventEmitter<Events extends Record<string, unknown>> {
  private listeners: { [K in keyof Events]?: Set<Listener<Events[K]>> } = {};

  on<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {
    const set = (this.listeners[event] ??= new Set());
    set.add(listener);
    return () => set.delete(listener);
  }

  emit<K extends keyof Events>(event: K, payload: Events[K]): void {
    for (const listener of this.listeners[event] ?? []) listener(payload);
  }
}

type ShopEvents = { orderPlaced: { orderId: string; totalPence: number }; orderCancelled: { orderId: string } };

export const shopEvents = new EventEmitter<ShopEvents>();
  • on returns an unsubscribe function: always clean up listeners to avoid memory leaks (just like effect clean-ups, Lesson 166).
  • The generic Events map makes emit("orderPlaced", { orderId: "1" }) a type error because totalPence is missing.

The observer pattern is everywhere: DOM addEventListener (Lesson 88), Node's EventEmitter, RxJS observables (Nest interceptors, Lesson 209), React state subscriptions, and, at system scale, pub/sub messaging (Lesson 236).

How to say it in an interview

"Design patterns are named solutions to recurring problems. A factory hides object creation behind a function that returns the right implementation of an interface. Strategy makes an algorithm interchangeable, like shipping cost calculators passed into checkout, so new behaviour is added without editing existing code; in JavaScript it is often just a function. Observer lets subscribers react to events from a subject without the subject knowing them, as in DOM events, Node's EventEmitter, RxJS and pub/sub; I always return an unsubscribe function to avoid leaks. I use patterns when they solve a real problem."

Key words

WordMeaning
Design patternA named, reusable solution to a common design problem
FactoryCreates objects without exposing which concrete class
StrategyInterchangeable algorithms behind one interface
ObserverSubscribers notified when a subject emits events
UnsubscribeRemoving a listener to prevent leaks

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.