Classic Design Patterns
Recognize and apply the most useful design patterns (strategy, factory, observer, decorator, adapter and singleton) and know when to skip them.
Welcome back!
Step 1 of 14Learn
Named solutions to recurring problems
In 1994, four authors published Design Patterns: Elements of Reusable Object-Oriented Software, cataloging 23 solutions that kept appearing in well-designed systems. The authors became known as the "Gang of Four", and their patterns became a shared vocabulary. Saying "use a strategy here" communicates a whole design in three words.
A pattern is not a library you install. It's a named arrangement of classes and objects that solves a common design problem, which you adapt to your own code.
You've already used one. The shipping example from the SOLID lesson was the strategy pattern:
- Problem: an algorithm needs to vary (shipping rules, sorting order, payment method, compression type), and you don't want a growing switch statement.
- Solution: put each variant in its own object with the same method, and give the main object a field holding the current strategy.
class Checkout {
constructor(pricing) { this.pricing = pricing; } // the strategy
total(items) { return this.pricing.apply(items); }
}
const regular = { apply: (items) => sum(items) };
const blackFriday = { apply: (items) => sum(items) * 0.7 };
const checkout = new Checkout(regular);
checkout.pricing = blackFriday; // swap behavior at run timeIn JavaScript and Python, a strategy is often just a function passed as an argument. array.sort((a, b) => a.price - b.price) is the strategy pattern in one line: the sort algorithm stays fixed, and the comparison strategy varies.
Step 2 of 14Practice · True or false
A design pattern is a ready-made code library that you download and add to your project.
Step 3 of 14Diagram
The strategy pattern in Checkout
Tap a shape with to see more.
- Checkout
- pricing (the strategy)
A field holding any object with apply(items).
- regular
apply = plain sum.
- blackFriday
apply = sum × 0.7. Swapped in at run time.
- total(items)
Never changes: it just delegates to pricing.apply().
Step 4 of 14Learn
Factory and observer
Factory: object creation sometimes involves decisions, such as which class to instantiate or how to configure it. Scattering those decisions across the codebase repeats them everywhere. A factory gathers creation in one place:
class ShapeFactory {
static create(spec) {
switch (spec.type) {
case 'circle': return new Circle(spec.r);
case 'rect': return new Rect(spec.w, spec.h);
default: throw new Error('Unknown shape: ' + spec.type);
}
}
}
const shapes = savedData.map(ShapeFactory.create);This is the one place where a switch on type is perfectly fine: it turns raw data into the right objects, and everything after that uses polymorphism.
Observer: one object (the subject) keeps a list of other objects (observers) and notifies all of them when something happens, without knowing what they do.
class Stock {
#observers = [];
#price = 0;
subscribe(fn) { this.#observers.push(fn); }
set price(p) {
this.#price = p;
this.#observers.forEach(fn => fn(p)); // notify everyone
}
}
const s = new Stock();
s.subscribe(p => chart.update(p));
s.subscribe(p => { if (p > 100) alerts.send('Above 100'); });
s.price = 104; // chart updates and the alert firesThe stock has no idea charts or alerts exist; new observers can be added without touching it. Browser events (addEventListener), Node's EventEmitter and reactive UI frameworks are all built on this pattern.
Step 5 of 14Practice · Match the pairs
Match each problem to the pattern that fits it.
Tap an answer, then tap the place where it belongs (or drag it there).
- Users choose between several tax-calculation rules at checkout
- Saved JSON records must be turned into the right subclass objects
- A dashboard, an email alert and a log must all react when an order is placed
- Your code expects
send(msg), but a new SMS library offerstransmit(phone, text) - You want to add caching around an existing data source without changing it
Step 6 of 14Diagram
Observer: one change, many reactions
Tap a shape with to see more.
- Stock (subject): price = 104
- chart.update(p)
- alert if p > 100
- any future observer
Added with subscribe(); Stock is never edited.
Step 7 of 14Learn
Decorator, adapter and the singleton warning
Decorator: wrap an object in another object with the same interface that adds behavior before or after delegating.
class CachedSource {
constructor(source) { this.source = source; this.cache = new Map(); }
get(key) {
if (!this.cache.has(key)) this.cache.set(key, this.source.get(key));
return this.cache.get(key);
}
}
const data = new CachedSource(new ApiSource()); // same get() interfaceDecorators stack: new LoggedSource(new CachedSource(new ApiSource())). This is composition solving the class-explosion problem from earlier.
Adapter: wrap an object to give it a different interface that your code expects. If your code calls notifier.send(message) but a vendor library offers client.transmit(number, text), a small SmsAdapter class with a send method that calls transmit lets the library fit in without changing either side.
Singleton: guarantee that a class has exactly one instance with global access. It's the most famous pattern and the most criticized. A singleton is global state in disguise: any code can reach it and change it, hidden dependencies pile up, and tests interfere with each other through the shared instance. Modern practice usually prefers creating one instance at startup and injecting it where needed. You still get one instance, but dependencies stay visible and tests can pass in a fake.
The broader lesson: patterns are tools. Forcing a factory, a strategy and an observer into a 50-line program makes it harder to read. Reach for a pattern when you recognize its problem in your code.
Step 8 of 14Practice · Code challenge
Implement the observer pattern. Write a class EventBus with subscribe(fn), which registers a listener function, and publish(value), which calls every listener with value in the order they subscribed and returns how many listeners were notified.
(() => { const b = new EventBus(); const got = []; b.subscribe(v => got.push("a" + v)); b.subscribe(v => got.push("b" + v)); b.publish(1); return got; })()(() => { const b = new EventBus(); b.subscribe(() => {}); b.subscribe(() => {}); b.subscribe(() => {}); return b.publish("x"); })()new EventBus().publish(5)(() => { const b = new EventBus(); let total = 0; b.subscribe(v => total += v); b.publish(2); b.publish(5); return total; })()
Step 9 of 14Practice · What would you do?
What would you do?
A teammate proposes making the app's Database connection a singleton so that "any class can just call Database.getInstance() whenever it needs data." What's the strongest concern to raise?
Step 10 of 14Note
Step 11 of 14Learn
More patterns worth recognizing
The Gang of Four catalog has 23 patterns, and you'll meet several others in libraries and frameworks:
- Builder constructs a complex object step by step:
new QueryBuilder().select('name').from('users').where('age > 18').build(). It avoids constructors with ten confusing parameters. - Command turns a request into an object with an
execute()method (and oftenundo()). Text editors keep a list of command objects to support undo and redo. - Iterator gives sequential access to a collection without exposing how it's stored. JavaScript's
for...ofand Python'sforloops are built on iterators. - Composite treats single objects and groups the same way. A folder and a file can both answer
size(); a folder's size is the sum of its children's. - Template method, which you saw with abstract classes, fixes an algorithm's outline in a parent and lets subclasses fill in steps.
- Facade offers one simple interface over a complicated subsystem, such as a
VideoConverter.convert(file, 'mp4')that hides codecs and buffers.
You don't need to memorize all of them. Learn to recognize the problem each one solves, and look up the details when that problem appears in your own code.
Step 12 of 14Practice · Match the pairs
Match each pattern to the problem it solves.
Tap an answer, then tap the place where it belongs (or drag it there).
- Builder
- Command
- Composite
- Facade
Step 13 of 14Flashcards
Spot the pattern in the wild
Tap a card to flip it.
Step 14 of 14Practice · Choose one
A logging wrapper implements the same save(record) method as the repository it wraps, logs each call, then calls the real repository. Which pattern is this?
Lesson complete!