Design Patterns: Which One When
A design pattern is a named solution to a problem that keeps coming up in object-oriented code. "Swap the algorithm without editing the class that uses it" is a problem; Strategy is its name. "Tell several objects when something happens, without knowing who they are" is a problem; Observer is its name. The value of the names is that you and your interviewer can say one word instead of drawing five boxes.
The classic catalog has 23 patterns, plus many more since. You don't need most of them in an interview. About a dozen show up again and again in LLD problems, and three or four do most of the work. This post is a map: what the three families are, which patterns matter, the symptom that should make you reach for each one, and how to tell the look-alikes apart. Each pattern has its own post for the details.
🗺️ In one sentence: pick a pattern by the symptom in front of you (a growing
ifon type, a constructor with ten arguments, a class that must notify others), not by scanning a list of patterns for one to use.
The Problem It Solves
Without patterns, the same design mistakes get reinvented in every codebase. Here is a typical first draft for an order in a food delivery app.
class Order:
def __init__(self, order_id: str, customer: Customer, restaurant: Restaurant) -> None:
self.order_id = order_id
self.customer, self.restaurant = customer, restaurant
self.status = "placed"
def advance(self, event: str) -> None:
if self.status == "placed" and event == "accept":
self.status = "preparing"
self.restaurant.print_ticket(self)
elif self.status == "preparing" and event == "ready":
self.status = "ready"
courier = min(couriers, key=lambda c: c.distance_to(self.restaurant)) # nearest
courier.assign(self)
elif self.status == "ready" and event == "pickup":
self.status = "on_the_way"
elif self.status == "on_the_way" and event == "deliver":
self.status = "delivered"
else:
raise ValueError(f"can't {event} when {self.status}")
sms.send(self.customer.phone, f"Your order is {self.status}")
email.send(self.customer.email, f"Order {self.order_id}: {self.status}")
analytics.track("order_status", self.order_id, self.status)
Three separate design problems are tangled in one method, and each is a problem a pattern was named for:
- The status rules are an
ifchain over (state, event) pairs. Adding "cancelled" means touching several branches, and nothing stops a typo like"preparng". That is the State pattern's problem. - Courier assignment is one hard-coded rule ("nearest"). The business will want "least busy" and "highest rated" next. That is Strategy's problem.
- Notifications are wired in directly. Adding push notifications or a loyalty-points service means editing
Order, which has no reason to know they exist. That is Observer's problem.
Knowing the patterns lets you spot those three problems in thirty seconds, name them, and fix each one in a standard way that your interviewer recognizes.
How It Works
Patterns are grouped into three families by what they deal with.
- Creational patterns are about making objects: hiding which class gets created, or building a complex object step by step.
- Structural patterns are about putting objects together: wrapping, adapting or grouping objects so they fit an interface.
- Behavioral patterns are about how objects talk and share work: who decides, who gets notified, how a request moves.
Here are the ones worth knowing for interviews, each with the symptom that should make you think of it.
Creational
| Pattern | Reach for it when... | Classic example |
|---|---|---|
| Factory | the caller knows what it wants by name or config, but shouldn't know the concrete class | "sms" → SmsChannel() |
| Builder | a constructor has many optional parameters, or the object must be valid and immutable once built | a pizza, an HTTP request |
| Singleton | there must be exactly one instance... and you can't simply pass one around (rarer than it sounds) | a process-wide config |
Structural
| Pattern | Reach for it when... | Classic example |
|---|---|---|
| Adapter | a class you don't control has the wrong interface | wrapping two payment providers |
| Decorator | you want to stack optional extras on an object without a subclass per combination | pizza toppings, logging around a call |
| Facade | callers need one simple entry point over several subsystems | HomeTheater.watch_movie() |
| Composite | items and groups of items should be treated the same way (a tree) | files and folders |
| Proxy | something must sit in front of an object with the same interface: lazy load, cache, access check | a caching image loader |
Behavioral
| Pattern | Reach for it when... | Classic example |
|---|---|---|
| Strategy | one job can be done several ways, and the caller picks | fare rules, eviction policy |
| State | an object behaves differently depending on its status, and moves between statuses | vending machine, order lifecycle |
| Observer | several objects must react when something happens, and the source shouldn't know them | order status notifications |
| Command | a request must be stored, queued, logged or undone | text editor undo |
| Chain of Responsibility | a request passes through handlers until one deals with it | expense approvals, middleware |
| Template Method | an algorithm's steps are fixed but some steps vary | a turn-based game loop |
| Iterator | callers need to walk a collection without knowing how it is stored | playlist, paged results |
If you only have time to learn four well, learn Strategy, State, Observer and Factory. Between them they cover most extensibility follow-ups: "add a new algorithm," "add a new status," "notify someone new" and "add a new type."
💡 Interview tip: the tables above are organized by symptom on purpose. In an interview, you never start from the pattern; you start from a requirement ("operators choose the assignment rule") and the symptom leads you to the pattern.
A Worked Example
Let's fix the order from the first section, one symptom at a time, and stop when the design is good enough.
Symptom 1: courier assignment will vary. One job, several ways, chosen by configuration. That is Strategy.
class AssignmentStrategy(ABC):
@abstractmethod
def pick(self, couriers: list[Courier], order: "Order") -> Courier | None: ...
class NearestCourier(AssignmentStrategy):
def pick(self, couriers: list[Courier], order: "Order") -> Courier | None:
free = [c for c in couriers if c.is_free()]
return min(free, key=lambda c: c.distance_to(order.restaurant), default=None)
Symptom 2: other parts of the system react to status changes. SMS, email and analytics all want to know when
the status changes, and more listeners are coming. Order shouldn't know any of them. That is Observer: the order
keeps a list of listeners and calls each one.
class OrderListener(ABC):
@abstractmethod
def on_status_change(self, order: "Order") -> None: ...
class SmsNotifier(OrderListener):
def on_status_change(self, order: "Order") -> None:
sms.send(order.customer.phone, f"Your order is {order.status.value}")
Symptom 3: status rules. Here we have a choice. The full State pattern gives each status its own class. But these statuses barely behave differently; they mostly decide which event is allowed next. A transition table and an enum say the same thing in less code, so that is what we use.
class Status(Enum):
PLACED = "placed"
PREPARING = "preparing"
READY = "ready"
ON_THE_WAY = "on the way"
DELIVERED = "delivered"
NEXT: dict[tuple[Status, str], Status] = {
(Status.PLACED, "accept"): Status.PREPARING,
(Status.PREPARING, "ready"): Status.READY,
(Status.READY, "pickup"): Status.ON_THE_WAY,
(Status.ON_THE_WAY, "deliver"): Status.DELIVERED,
}
The result. Order now coordinates instead of doing everything.
class Order:
def __init__(self, order_id: str, customer: Customer, restaurant: Restaurant,
listeners: list[OrderListener]) -> None:
self.order_id, self.customer, self.restaurant = order_id, customer, restaurant
self.status = Status.PLACED
self.listeners = listeners
def advance(self, event: str) -> None:
new_status = NEXT.get((self.status, event))
if new_status is None:
raise InvalidTransition(self.status, event)
self.status = new_status
for listener in self.listeners:
listener.on_status_change(self)
Courier assignment moves out of Order into the dispatcher that owns the couriers, which holds an
AssignmentStrategy and listens for READY, so it is just one more listener.
Checking it against the follow-ups. "Add push notifications" is one new OrderListener. "Assign the least
busy courier at peak hours" is one new strategy. "Add cancellation from PLACED or PREPARING" is two new rows in
the table. None of them edits advance. If a later follow-up gives statuses real behavior of their own (refund
rules that differ per status, timers per status), that is the moment to upgrade the table to the State pattern.
⚠️ Common mistake: applying every pattern you can name. We also could have added a Factory for orders, a Builder for the constructor and a Singleton dispatcher. None of them fixes a symptom this design has, so none of them belongs on the board.
When Not to Use It
Patterns cost something: extra classes, extra indirection, and more for the reader to hold in mind. Skip them when:
- There is no variation. One pricing rule and no hint of a second is a method, not a strategy. Say you would extract an interface when a second rule appears.
- The difference is data, not behavior. Ride types that differ only in rates need a table of numbers, not a class each.
- The language already does it. Python functions are first-class, so a one-method strategy can be a function.
Python's
forloop and generators are the Iterator pattern. A module with functions is often a better "singleton" than a Singleton class. - You can't name the symptom. If you can't finish the sentence "I'm using X because...", you are pattern matching, not designing.
The design principles post calls this YAGNI: build the extension point the requirements or the interviewer's hints ask for, and nowhere else.
In LLD Interviews
Most problem breakdowns lean on two or three patterns. These pairings come up the most:
| Problem | Patterns that usually appear |
|---|---|
| Parking Lot | Strategy (fees, spot selection), Factory (spot or vehicle types) |
| Vending Machine | State (idle, has money, dispensing) |
| Elevator | Strategy (dispatching), State (moving, idle, doors open) |
| Text Editor | Command (undo/redo) |
| Pizza Ordering | Decorator or Builder (toppings), Strategy (promotions) |
| Notification Service | Factory (channels), Observer, Strategy (retry policy) |
| File System | Composite (files and directories) |
| Logging Framework | Chain of Responsibility (levels), Observer (appenders), Singleton |
| Payment System | Adapter (providers), Strategy (routing), State (payment status) |
| Chess | Strategy (piece moves), Command (move history) |
How to bring patterns up. Introduce a pattern at the moment a requirement calls for it, in one sentence that names the symptom: "Assignment rules vary and the operator picks one, so I'll put them behind a strategy interface." Draw the interface and one or two implementations; list the rest by name. Don't open with "I'll use the Strategy, Observer and Factory patterns" before you have entities. Interviewers grade the fit, not the count.
When the interviewer names one. If you hear "how would you make this extensible?" without a pattern being named, it is a chance to show judgment: pick the one symptom most likely to grow and fix that. If they ask "could you use the State pattern here?", answer with the trade-off: what it would buy, what it would cost, and whether this problem needs it yet.
Related Patterns
The patterns most often confused are the ones that look the same on a class diagram. The difference is always intent: why the extra object exists.
- Strategy vs State. Both hold a swappable object behind an interface. In Strategy, the client picks the algorithm and it rarely changes. In State, the states switch the context themselves as events arrive.
- Decorator vs Proxy vs Adapter. All three wrap another object. A decorator keeps the interface and adds behavior, and you can stack several. A proxy keeps the interface and controls access (lazy loading, caching, permission checks). An adapter changes the interface so a class fits where it otherwise wouldn't.
- Factory vs Builder. A factory decides which class to create, usually in one call. A builder assembles one object from many optional parts, step by step.
- Observer vs Chain of Responsibility. Observer delivers an event to every listener. A chain passes a request along until one handler deals with it.
- Command vs Strategy. Both wrap behavior in an object. A command is a request to run later, queue or undo; a strategy is a way of doing a job the context runs now.
- Facade vs Adapter. A facade simplifies many classes behind one new interface; an adapter makes one class match an existing interface.
- Template Method vs Strategy. Template Method varies steps through inheritance (subclasses override hooks); Strategy varies the whole algorithm through composition and can be swapped at runtime.
Summary
- A design pattern is a named, standard fix for a recurring design problem. The name is shared vocabulary with your interviewer.
- Creational patterns make objects (Factory, Builder, Singleton), structural patterns combine them (Adapter, Decorator, Facade, Composite, Proxy), behavioral patterns coordinate them (Strategy, State, Observer, Command, Chain of Responsibility, Template Method, Iterator).
- Learn Strategy, State, Observer and Factory first; they answer most extensibility follow-ups.
- Choose by symptom: varying algorithm → Strategy; behavior depends on status → State; others must react → Observer; create by name → Factory; many optional parts → Builder; undo or queue → Command.
- Use the lightest form that fixes the symptom (a function, a table, an enum) and upgrade only when a follow-up needs it.
- Look-alikes differ in intent: say why the extra object exists, and the right name follows.