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.
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.
Checkout's if / else grows every time you add a way to pay, and you have to test the whole thing again
Before · Checkout picks the if branch itself, and every way to pay lives in one file
Switch between before and after, then press "Ask for a change" to see how many existing parts you'd have to edit. A box you'd edit gets a red "edit" tag; anything added gets a "new" tag.
A shop needs several ways to work out shipping (by weight, flat rate, free over a minimum spend), picked while the program runs.
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.
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.
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
| pattern | Problem | Don't use it when |
|---|---|---|
| Strategy | Checkout's if / else grows every time you add a way to pay, and you have to test the whole thing again | 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 |
| Observer | Order 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 job | One listener that never changes: a direct call reads better. Listeners' order and errors get harder to follow, and a forgotten unsubscribe = a memory leak |
| Factory | Every place that sends a message decides for itself whether to new EmailSender or SmsSender, so the same choosing code is spread over many files | There's only one kind, or you only make it in one place: call the constructor directly. Don't build a factory of factories |
| Adapter | The library logs with write(level, text), but our code wants to call info() / error(). Call the library directly and every file gets tied to it | If you can make one side match the other yourself, that's simpler. Adapters stacked several deep hide cost and bugs |
| Decorator | fetchOrders has logging, retry and fetch code mixed together. Another fetch that wants retry has to copy it | Deep 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 |
| Singleton | Several parts create their own Config: separate objects, the file / env read again each time, and the values may not match | It'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) |
| Builder | Order 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 it | Only a few values: a constructor is enough. TypeScript / Python can already pass an object or named keywords. Go prefers functional options |
| Proxy | Prices come from an API that's slow and charges per call, and several pages ask for the same prices over and over | It'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 |
| Facade | One order has to call stock, payment and shipping in sequence, and every page that places orders writes that sequence again itself | There'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 |
| Command | Buttons call Cart directly: if you want undo, a history, or to run actions later, you have to change every button | Actions 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: 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));
node strategy.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: PromptPay QR for 450 THBTypeScript: 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.