DevPath
Tracks

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.

price_aftercaller
discount(price)one calling convention
percent(10)
fixed(50)
Strategy: the caller depends only on the shared calling convention. Swapping percent for fixed changes the pricing rule without editing the caller.

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.

place_orderknows only a name and a value
make_discount(kind, value)factory: looks up the name
percent(value)
fixed(value)
Factory: callers say what they want by name, and one function decides which concrete discount to build. A new kind is added in one place.

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.

place_orderpublisher
EventBustopic: placed
email receipt
reserve stock
Observer: place_order only talks to the bus. Listeners subscribe to a topic, so a third one can be added without touching the order code.
place_orderEventBusemail listenerstock listenerpublish placed, 180call listener(180)call listener(180)
One publish fans out to every subscriber in subscription order. The publisher waits for all of them, which is why a slow or failing listener hurts the order code.

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.

place_order
logged wrapperrecords the call
price_afterreal function
discount(price)
Decorator: logged has the same signature as price_after, so callers cannot tell the difference. It adds a record, then delegates.
 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).

OperationTimeNotes
StrategyReplaces if/elif chainsOpen for new behaviors, closed for edits
ObserverO(listeners) per eventBeware slow or failing listeners
DecoratorO(1) wrapper costStack depth adds up; debugging gets harder
FactoryO(1) dispatchOne 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])

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

Related lessons