Design Patterns That Actually Get Used
Strategy, observer, factory, and decorator in a few lines each, plus why singletons deserve suspicion, and how to tell when a pattern helps instead of over-engineering.
intermediate40 min#design-patterns#strategy#observer#factory#decorator#singleton
Prerequisites: Testing: Unit, Integration, and Test Doubles
Why it matters
A design pattern is a named, proven solution to a problem that keeps recurring. The value is mostly vocabulary: saying "use a strategy here" tells a teammate in four words what would take a paragraph to describe. Patterns also help in interviews, where "how would you design the pricing rules?" is a pattern question in disguise. They are tools, not goals: used where the problem exists they simplify code; used everywhere they bury it.
Intuition
Carpenters name joints: dovetail, mortise and tenon. Each joint is a known answer to "how do I connect these two boards so they hold?" Software has the same recurring joints, such as swapping behavior, notifying interested parties, building objects without hard-coding their class, and adding features around existing code. Learning the names lets you recognize the situation and recall the trade-offs.
The underlying principles matter more than the names: depend on small interfaces, favor composition over inheritance, and keep each piece with one reason to change.
How it works
Strategy: swap an algorithm at runtime. Put each interchangeable behavior behind one calling convention, and let the caller choose. Use it when you find a growing if kind == "a" ... elif kind == "b" chain. In Python and JavaScript, a strategy is often just a function, since functions are values; no class hierarchy needed.
Factory: centralize creation. A function decides which concrete thing to build from a name or config, so callers do not need to know the concrete types. Use it when creation logic is nontrivial or likely to change, such as picking a payment provider from configuration.
Observer (publish/subscribe): notify without coupling. A subject keeps a list of listeners and calls each when something happens. The publisher knows nothing about who is listening, so you can add "send email" or "update stock" later without editing the order code. This is the idea behind DOM events, Node's EventEmitter, and message queues.
Decorator: add behavior around existing behavior. Wrap a function or object in another with the same interface that adds logging, caching, retries, or timing, then delegates. Python's @decorator syntax and JavaScript higher-order functions make this natural. Wrappers stack, and each does one thing.
caller --> [logging] --> [retry] --> [real function]
wraps wraps
Singleton: one instance, with caveats. A singleton guarantees a single instance with global access. It is also global mutable state in a costume: it hides dependencies (functions use it without declaring it), makes tests interfere with one another, and makes concurrency harder. Prefer creating one object at startup and passing it to whoever needs it (dependency injection). In Python, a module-level object is already a singleton without any ceremony.
Other patterns worth recognizing. Adapter (translate one interface to another, such as wrapping a third-party SDK), Builder (construct complex objects step by step), Command (turn an action into an object for queues and undo), Iterator (built into both languages through iteration protocols).
| Operation | Time | Notes |
|---|---|---|
| Strategy | Replaces if/elif chains | Open for new behaviors, closed for edits |
| Observer | O(listeners) per event | Beware slow or failing listeners |
| Decorator | O(1) wrapper cost | Stack depth adds up; debugging gets harder |
| Factory | O(1) dispatch | One place to add a new type |
Code: four patterns in one small order system
The pricing rule is a strategy created by a factory, placing an order publishes an event to observers, and a decorator logs calls to the price function.
# Strategy + factory: discounts are plain functions chosen by name.
def percent(p):
return lambda price: price * (100 - p) // 100
def fixed(amount):
return lambda price: max(price - amount, 0)
def make_discount(kind, value): # factory
makers = {"percent": percent, "fixed": fixed}
if kind not in makers:
raise ValueError(f"unknown discount: {kind}")
return makers[kind](value)
# Decorator: add logging without touching the wrapped function.
calls = []
def logged(fn):
def wrapper(*args):
calls.append(f"{fn.__name__}{args}")
return fn(*args)
return wrapper
# Observer: a tiny event bus.
class EventBus:
def __init__(self):
self.listeners = {}
def subscribe(self, topic, fn):
self.listeners.setdefault(topic, []).append(fn)
def publish(self, topic, payload):
for fn in self.listeners.get(topic, []):
fn(payload)
bus = EventBus()
log = []
bus.subscribe("placed", lambda total: log.append(f"email receipt for {total}"))
bus.subscribe("placed", lambda total: log.append(f"reserve stock for {total}"))
@logged
def price_after(discount, price):
return discount(price)
def place_order(price, kind, value):
total = price_after(make_discount(kind, value), price)
bus.publish("placed", total)
return total
print(place_order(200, "percent", 10), place_order(200, "fixed", 50))
print(log)
print(len(calls), calls[0].split("(")[0])// Strategy + factory: discounts are plain functions chosen by name.
const percent = (p) => (price) => Math.floor((price * (100 - p)) / 100);
const fixed = (amount) => (price) => Math.max(price - amount, 0);
function makeDiscount(kind, value) { // factory
const makers = { percent, fixed };
if (!(kind in makers)) throw new Error(`unknown discount: ${kind}`);
return makers[kind](value);
}
// Decorator: add logging without touching the wrapped function.
const calls = [];
function logged(fn, name) {
return (...args) => {
calls.push(name);
return fn(...args);
};
}
// Observer: a tiny event bus.
class EventBus {
constructor() {
this.listeners = new Map();
}
subscribe(topic, fn) {
if (!this.listeners.has(topic)) this.listeners.set(topic, []);
this.listeners.get(topic).push(fn);
}
publish(topic, payload) {
for (const fn of this.listeners.get(topic) ?? []) fn(payload);
}
}
const bus = new EventBus();
const log = [];
bus.subscribe("placed", (total) => log.push(`email receipt for ${total}`));
bus.subscribe("placed", (total) => log.push(`reserve stock for ${total}`));
const priceAfter = logged((discount, price) => discount(price), "price_after");
function placeOrder(price, kind, value) {
const total = priceAfter(makeDiscount(kind, value), price);
bus.publish("placed", total);
return total;
}
console.log(placeOrder(200, "percent", 10), placeOrder(200, "fixed", 50));
console.log(log.join(" | "));
console.log(calls.length, calls[0]);The first line of output is 180 150 in both languages. The second line differs only in formatting: Python prints the list ['email receipt for 180', 'reserve stock for 180', 'email receipt for 150', 'reserve stock for 150'], while JavaScript prints the same four entries joined by |. The third line is 2 price_after: two calls were logged under the name price_after.
Adding a new discount (say, buy-one-get-one) means one new function and one entry in the factory. Adding a new reaction to an order means one new subscribe. place_order never changes.
Common pitfalls
- Pattern hunting: start with the simplest code and introduce a pattern when a concrete pain (a growing conditional, duplicated wiring, painful tests) shows up.
- Singleton overuse: global state couples distant code and makes tests order-dependent. Inject dependencies instead.
- Observer memory leaks: listeners that are never unsubscribed keep objects alive, and long chains of events make control flow hard to follow.
- Listener exceptions: one failing observer can stop the rest of the notifications. Decide whether to catch and log, or let it propagate.
- Deep decorator stacks: order matters (retry around logging differs from logging around retry) and stack traces get noisy.
- Inheritance where composition fits: deep class trees are rigid. Compose small parts.
Practice
Replace a conditional with a strategy easy
Hint
What do all branches have in common?
Show solution
Code does if fmt == "json": ... elif fmt == "csv": .... Make a dictionary {"json": to_json, "csv": to_csv} of functions with the same signature and call formatters[fmt](data). Adding a format is one new entry; unknown formats raise a clear error in one place.
Build a memoize decorator medium
Hint
Wrap the function and keep a dictionary keyed by the arguments.
Show solution
The wrapper builds a key from the arguments, returns the stored value on a hit, otherwise calls the function, stores, and returns. It only works for pure functions with hashable arguments. Python ships functools.cache; building it once teaches how decorators capture state in a closure.
Observer with unsubscribe medium
Hint
subscribe should return something that undoes it.
Show solution
Have subscribe return a function that removes the listener from the list. When iterating in publish, iterate over a copy so a listener that unsubscribes itself does not skip the next one. This also addresses the memory leak pitfall.
Make a singleton testable hard
Hint
Ask who needs the object, and how they get it.
Show solution
Instead of Database.instance() called deep inside functions, create the connection once in the application entry point and pass it as a parameter or constructor argument. In production, main builds the real database; in tests, pass a fake or in-memory one. You get the single instance in practice without global access, and every function now states its dependencies.
Interview questions
- Name some patterns you have used and why. Pick two real ones with the problem each solved, such as strategy for pricing rules and observer for event notifications.
- Strategy versus if/else? Strategy makes behaviors independently addable and testable and respects the open/closed principle; a simple two-branch condition does not need it.
- Why is the singleton considered an anti-pattern by many? Hidden global state, tight coupling, hard testing, concurrency issues. Prefer dependency injection with one instance created at startup.
- Decorator versus inheritance? Decorators add behavior at runtime and can be combined in any order; inheritance fixes behavior at compile time and leads to class explosions.
- How does observer relate to message queues? Same idea, but a queue adds durability, buffering, and decoupling across processes and machines.
Interviewers look for: choosing a pattern because of a stated problem, naming the trade-off, and showing restraint when a plain function is enough.
Quick check
A function has grown a chain of if/elif branches that each compute shipping cost differently for a carrier, and new carriers keep being added. Which pattern fits best?
Finished this lesson?
Further resources
- Software design pattern (Wikipedia) (article)
- Refactoring Guru: Design Patterns (article)