Design patterns

Problems that keep coming back, and fixes with names. Watch the boxes and arrows change shape and send a job through them, then ask for a change and count how many existing parts you'd have to edit. Each one also says when not to use it.

Level: IntermediateWatch 10 patterns · ~70 secondsBefore / after · ask for a changeCompare all 10 at onceRecall: match 10 · 16 cardsTypeScript · Go · Python

What you'll take away

  • Turn a growing if / else into Strategy, and know when a short if reads better
  • Let an Order announce events with Observer, and watch for a forgotten unsubscribe
  • Tell Decorator from Proxy: layers that add abilities vs a stand-in nobody notices
  • Pass config in at startup instead of a Singleton, so tests can swap the values

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
BeforeSeveral ways to pay
Checkout.pay() if … else if …
Card
PromptPay
COD
Checkout picks the if branch itself, and every way to pay lives in one file
Step 1 / 10 · step by step
Strategypattern
Beforestructure
4boxes in the picture
–existing parts to edit
–new parts added

A box is a class, an interface (dashed) or a function. A solid arrow is a call; a dashed purple one means "is a kind of" (implements). A moving dot is one job. Every example is made up for this lesson.

Step 4 · Every option at once, on one clock

Compare them all: Design patterns

Every pattern does its job at the same time, on one clock. Switch the whole grid between before and after, then press "Ask every tile for a change" to send each pattern its own change request at once: see which ones take it without editing existing code, and which ones can't.

0.0 s
StrategySeveral ways to payCheckout calls pay() on whatever method it holds, without knowing which one it is

Use it when Checkout's if / else grows every time you add a way to pay, and you have to test the whole thing again

Skip it when Only 2–3 ways that hardly ever change: a short if / else reads better. In a language that can pass functions around, one function is enough

A red "edit" tag marks an existing part you have to edit, a "new" tag marks something added. Every example is made up for this lesson. Press any tile to see it large above, with when it fits.

A pattern is a name for a fix you keep needing

It isn't a library and it isn't a rule: it's a short name a team uses to say which kind of fix they mean. The best-known set comes from the book Design Patterns (1994) by four authors known as the Gang of Four. Every pattern buys flexibility with more indirect code, so use one when the problem has actually shown up, not just in case.

The ten in this lesson

patternProblemDon't use it when
StrategyCheckout's if / else grows every time you add a way to pay, and you have to test the whole thing againOnly 2–3 ways that hardly ever change: a short if / else reads better. In a language that can pass functions around, one function is enough
ObserverOrder calls email, stock and analytics itself, one by one, so it has to know every one of them, and you edit Order whenever there's a new jobOne listener that never changes: a direct call reads better. Listeners' order and errors get harder to follow, and a forgotten unsubscribe = a memory leak
FactoryEvery place that sends a message decides for itself whether to new EmailSender or SmsSender, so the same choosing code is spread over many filesThere's only one kind, or you only make it in one place: call the constructor directly. Don't build a factory of factories
AdapterThe library logs with write(level, text), but our code wants to call info() / error(). Call the library directly and every file gets tied to itIf you can make one side match the other yourself, that's simpler. Adapters stacked several deep hide cost and bugs
DecoratorfetchOrders has logging, retry and fetch code mixed together. Another fetch that wants retry has to copy itDeep layers make debugging hard (long stack traces, and the order of layers matters). If it's used in one place, write it straight into that function
SingletonSeveral parts create their own Config: separate objects, the file / env read again each time, and the values may not matchIt's global state: every part depends on it without saying so, and tests can't swap the values. Usually it's better to create it once at startup and pass it in (dependency injection)
BuilderOrder has lots of optional values: in new Order("Thai tea", 2, null, null, true, …) you can't tell which value is which, and every new value means editing every place that calls itOnly a few values: a constructor is enough. TypeScript / Python can already pass an object or named keywords. Go prefers functional options
ProxyPrices come from an API that's slow and charges per call, and several pages ask for the same prices over and overIt's called rarely and it's already fast: an extra layer is just somewhere for bugs to hide (a stale cache). If you mean to stack layers to add features, that's Decorator
FacadeOne order has to call stock, payment and shipping in sequence, and every page that places orders writes that sequence again itselfThere's only one subsystem, or the caller has to control every step itself. A facade that grows to do everything turns into a god object
CommandButtons call Cart directly: if you want undo, a history, or to run actions later, you have to change every buttonActions you never undo or keep: call the function directly. In TypeScript / Python a do / undo pair of functions is enough, no class per command

In languages that pass functions as values

The book's examples are in C++ and Smalltalk and lean on classes. In TypeScript, Go and Python, a function can often stand in for Strategy (a payment function), Observer (a list of callbacks) and Decorator (a function that takes a function and returns one). In Go, define small interfaces on the side that uses them, and use a func when the behavior is a single method.

In real code

strategy.ts
// Strategy: many ways to do one job behind one interface; the checkout does not care which one it holds.
// Run: node strategy.ts
import assert from "node:assert/strict";

interface PaymentMethod {
  pay(amountBaht: number): string;
}

const card: PaymentMethod = { pay: (amount) => `card charged ${amount} THB` };
const promptPay: PaymentMethod = { pay: (amount) => `PromptPay QR for ${amount} THB` };

class Checkout {
  private method: PaymentMethod;
  constructor(method: PaymentMethod) {
    this.method = method;
  }
  use(method: PaymentMethod) {
    this.method = method;
  }
  total(amountBaht: number) {
    return this.method.pay(amountBaht);
  }
}

const checkout = new Checkout(card);
assert.equal(checkout.total(450), "card charged 450 THB");
checkout.use(promptPay); // a new way to pay, and Checkout did not change
assert.equal(checkout.total(450), "PromptPay QR for 450 THB");
console.log(checkout.total(450));
Run: node strategy.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: PromptPay QR for 450 THB

TypeScript: an interface and two objects. Go: a type PayFunc is enough, no interface needed. Python: a plain function is a strategy. The Load balancer lesson uses this pattern to pick a server.

Common questions

What is a design pattern, and do I need to know them all?

A short name for a fix to a problem that keeps coming back, so a team can say which fix they mean in one word. It isn't a library or a rule. You don't need them all by heart, just what problem each one solves. The best-known set comes from the Gang of Four book (1994).

When is Strategy better than a plain if / else?

The if / else grows every time you add a way to pay, and the whole thing needs testing again. With Strategy each way has the same shape, so a new one is one new file. But with only 2–3 ways that hardly change, a short if / else reads better.

Decorator vs Proxy: what's the difference?

They look alike because both wrap the real thing behind the same shape. A Proxy is a stand-in in front of it (caching, access checks, timing) and the caller doesn't notice. A Decorator means to stack layers, each adding one ability, like log → retry → fetch.

Why do people say Singleton is bad?

Because it's global state wearing a class. Every part depends on it without saying so, and a test that wants other values can't swap it. Usually it's better to create the config once at startup and pass it in (dependency injection).

What does a Factory buy me?

It puts the choice of what to make in one place. The caller just names the kind, like "sms", and gets a sender back, so adding push means changing createSender alone. With one kind, or one place that makes it, call the constructor directly.

What's the catch with Observer?

Order no longer needs to know anyone, but with many listeners their order and errors get harder to follow, and a forgotten unsubscribe leaves a listener hanging around for good: a memory leak. With one listener that never changes, a direct call reads better.

Do I still need these patterns in TypeScript, Go or Python?

The ideas still apply, but they get much smaller. One function can be a Strategy, a list of callbacks is an Observer, and a function that takes a function and returns one is a Decorator. The book's examples are in C++ and Smalltalk, which is why they lean on classes.

Next lesson

Monolith vs microservicesLevel: Intermediate

Patterns keep the parts of one codebase apart; next, when those parts should become services, and the modular monolith in between.