The Patterns Worth Knowing
The eleven design patterns that cover almost every LLD interview — what problem each one solves, the smallest useful example, and the phrase in the question that should make you reach for it.
A design pattern is just a named solution to a problem that keeps coming up. The name matters mainly because it lets two engineers skip a paragraph of explanation.
There are twenty-three classic ones. In an SDE-2 interview you will use about six, recognise four more, and lose points for forcing in the rest. This page is that working set, organised by the phrase in the requirements that should trigger it — because that's how you have to recall them when the clock is running.
| If the requirement says… | Reach for | Because |
|---|---|---|
| "…different / depending on / configurable" | Strategy | Swap one piece of logic for another |
| "…create the right kind of X based on input" | Factory | One place knows which class to build |
| "…tell everyone when Y happens" | Observer | One event, many listeners — and the sender doesn't need to know who they are |
| "…behaves differently while it's in state Z" | State | Only legal transitions, instead of a tangle of isPaid/isShipped flags |
| "…optional extras that combine" | Decorator | Stack behaviour without a class per combination |
| "…there must be exactly one" | Singleton | (Careful — see below) |
| "…lots of optional settings" | Builder | Readable construction, validated once |
| "…also support this other provider" | Adapter | Translate someone else's interface into yours |
| "…undo / schedule / queue an action" | Command | Turn the action itself into an object |
| "…where does the data come from" | Repository | Hide storage behind a collection-like interface |
#Strategy — the one you'll use most
The problem: one step of your logic has several versions, and you don't want the caller choosing between them with an if.
The idea: put that step behind an interface. Each version becomes a class. The caller holds the interface and doesn't care which version it got.
interface ParkingFeeStrategy {
Money calculate(Duration parked, VehicleSize size);
}
class HourlyFee implements ParkingFeeStrategy {
public Money calculate(Duration d, VehicleSize s) {
long hours = Math.max(1, d.toHours()); // round up, minimum one
return RATES.get(s).times(hours);
}
}
class FlatDayFee implements ParkingFeeStrategy { /* ... */ }
class ExitTerminal {
private final ParkingFeeStrategy pricing; // handed in, not created here
Money checkout(Ticket t) { return pricing.calculate(t.duration(), t.size()); }
}Say this: "Pricing is the requirement most likely to change, so it goes behind a strategy. A weekend surcharge becomes a new class rather than an edit."
Strategy is the workhorse because nearly every LLD problem hides one. Pricing, matching, ranking, eviction (choosing what to throw out of a full cache), retrying, routing, scheduling, discounting, splitting a bill — all strategies. When you're stuck for something intelligent to say about future changes, ask yourself: what is the policy in this system — the business rule someone will want to tweak, like how fees are worked out or which driver gets a ride? Then put it behind an interface.
#Factory — one place that knows how to build things
Two versions, and the difference is worth knowing:
- Simple factory — one method that maps an input to a concrete class. This is what you want about nine times out of ten.
- Abstract factory — builds a whole family of matching objects together (an entire
MacUiKitversus aWindowsUiKit). Rarely justified. Mention it only if the problem really has families.
class NotificationChannelFactory {
private final Map<ChannelType, Supplier<Channel>> registry = Map.of(
ChannelType.EMAIL, EmailChannel::new,
ChannelType.SMS, SmsChannel::new,
ChannelType.PUSH, PushChannel::new
);
Channel create(ChannelType type) {
Supplier<Channel> s = registry.get(type);
if (s == null) throw new UnsupportedChannelException(type);
return s.get();
}
}Say this: "The factory is the only place allowed to know every concrete channel. That stops that knowledge spreading through the codebase."
#Observer — announce it, don't call everyone
The problem: when something happens, several unrelated things need to react, and the thing that happened shouldn't have to know about any of them.
interface OrderListener { void onEvent(OrderEvent e); }
class Order {
private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
void addListener(OrderListener l) { listeners.add(l); }
private void publish(OrderEvent e) {
for (OrderListener l : listeners) l.onEvent(e); // see the caveat below
}
}
// Listeners: InventoryUpdater, EmailNotifier, AnalyticsLogger, LoyaltyPoints…Say this: "Placing an order publishes an event. Inventory, email and analytics each subscribe. Adding loyalty points later doesn't touch Order at all."
#State — when behaviour depends on what happened before
The problem: an object behaves differently depending on its current phase, and you're accumulating booleans (isPaid, isShipped, isCancelled) plus the tangle of ifs that check every combination.
The idea: make each phase its own object, and let each one decide what's allowed.
interface OrderState {
OrderState pay(Order o);
OrderState cancel(Order o);
}
class Created implements OrderState {
public OrderState pay(Order o) { o.chargeCard(); return new Paid(); }
public OrderState cancel(Order o) { return new Cancelled(); }
}
class Shipped implements OrderState {
public OrderState pay(Order o) {
throw new IllegalTransitionException("already paid");
}
public OrderState cancel(Order o) {
throw new IllegalTransitionException("already in transit");
}
}The payoff to name out loud: illegal moves become impossible rather than merely unlikely, and all the rules sit in one readable place. With booleans, nothing stops a bug from setting isShipped = true on an unpaid order. With state objects, a Created order has no method that ships it — the only way forward is through pay. This is the pattern for lifts, orders, bookings, ATMs, vending machines and traffic lights — see Elevator System, Vending Machine and ATM.
There's a lighter version that is often the better answer in 40 minutes: an enum of states plus a Map<State, Set<State>> listing which moves are legal. Fewer classes, same guarantee. Say you'd start there and move to state classes when each state grows real behaviour.
#Decorator — wrap to add behaviour
The problem: optional extras that combine freely. Subclassing every combination explodes, as it did in Objects, in practice.
The idea: each extra wraps the thing it decorates and adds a little on top.
interface Coffee { Money cost(); String description(); }
class Espresso implements Coffee { /* the base drink */ }
abstract class CoffeeAddOn implements Coffee {
protected final Coffee inner; // the thing being wrapped
protected CoffeeAddOn(Coffee inner) { this.inner = inner; }
}
class Milk extends CoffeeAddOn {
public Money cost() { return inner.cost().plus(Money.of(50)); }
public String description() { return inner.description() + " + milk"; }
}
Coffee order = new Milk(new Caramel(new Espresso())); // no class explosionTwo real examples worth mentioning: Java's new BufferedInputStream(new FileInputStream(...)), where the outer stream adds buffering around the inner one; and web middleware chains (auth → logging → rate limit → handler), where each layer wraps the next and adds one behaviour before passing the request on.
#Facade — one simple door into a complicated subsystem
The problem: doing one ordinary thing takes six objects in the right order. To check out a cart you call inventory to reserve, pricing to total, tax to calculate, payments to charge, and shipping to book — and every caller has to know that sequence.
The idea: put one class in front with a short, task-shaped method. It does the coordinating; callers just ask for the task.
class CheckoutFacade {
private final Inventory inventory;
private final Pricing pricing;
private final TaxCalculator tax;
private final PaymentGateway payments;
private final Shipping shipping;
Order checkout(Cart cart, Card card, Address to) {
Reservation r = inventory.reserve(cart.items());
Money total = tax.addTo(pricing.total(cart), to);
payments.charge(card, total);
Shipment s = shipping.book(r, to);
return Order.placed(cart, total, s);
}
}The subsystem's classes don't change and are still there for anyone who needs the detail. The facade just makes the common case easy and keeps the order of steps in one place.
How it differs from its neighbours — the comparison interviewers like:
| Pattern | Wraps | Changes the interface? | Purpose |
|---|---|---|---|
| Adapter | one object | yes — to the one you expect | make something fit |
| Decorator | one object | no — same interface | add behaviour on top |
| Facade | many objects | yes — a new, simpler one | hide a complicated sequence |
You'll recognise the facade in most LLD answers already: the ParkingLot, VendingMachine and ATM classes are facades over their parts. Saying so — "VendingMachine is the facade customers talk to; inventory, cash box and states sit behind it" — names the pattern without forcing it.
#Singleton — know the objections or skip it
The problem: you want exactly one instance of something, reachable from anywhere.
enum ConfigStore { INSTANCE; /* thread-safe and concise */ }The enum version is the one to write: Java itself guarantees exactly one INSTANCE, even with many threads. The older double-checked locking version — check if the instance is null, lock, check again, then create it — is a classic quiz question. Know that its field must be volatile (otherwise another thread can see a half-constructed object), and that most codebases have moved on.
#Builder — construction with many options
The problem: a constructor with eight parameters, half optional, and callers writing null, null, false, null.
Pizza p = new Pizza.Builder(Size.LARGE)
.thinCrust()
.addTopping(MUSHROOM)
.addTopping(OLIVE)
.extraCheese()
.build(); // all the checking happens here, onceThe point to make: the object is only ever handed out in a valid state. build() verifies the rules, so a half-built pizza never escapes. It also lets the finished object be immutable — all the setting happens on the builder, so the Pizza itself needs no setters. Immutable objects are safe to share between threads, which makes the threading follow-up much easier to answer.
#Adapter, Command, Repository — the quick three
Adapter wraps something with the wrong interface so it fits yours. The trigger is always integration: "we also need to support Stripe" or "there's this old library". class StripeAdapter implements PaymentGateway { private final StripeClient stripe; ... }. One class, one sentence, done.
Command turns an action into an object: interface Command { void execute(); void undo(); }. Trigger words: undo, redo, job queue, scheduling, macro, audit log. If a problem mentions undo, this is the answer and there isn't a close second.
Repository is an interface that looks like a simple collection — find things, save things — while hiding where the data actually lives (memory, a database, a file): interface SpotRepository { Optional<Spot> findFreeSpot(VehicleSize s); void save(Spot s); }. In an interview it lets you say "I'll assume an in-memory implementation, with a database behind it in production" and move on without designing a schema nobody asked for.
#Using patterns without sounding like a catalogue
Three rules:
- Requirement first, pattern second. Always state the pressure ("payment methods will grow") before the name ("so, strategy").
- One or two, used properly. A design using strategy and observer well beats one that name-drops six.
- Be willing to not use one. "I could put a factory here, but there's only one implementation, so I'd keep it simple until there's a second." That sentence shows judgement, which is the thing being graded.
#Check yourself
Strategy — the trigger and the idea?Show answer
Simple factory versus abstract factory?Show answer
What are the two observer follow-ups, and the answers?Show answer
State pattern — the payoff, and the lighter version?Show answer
Adapter versus decorator versus facade?Show answer
What is the senior answer on singletons?Show answer
Builder versus command versus repository — one trigger each.Show answer
How do you use patterns without sounding like a catalogue?Show answer
#What to carry forward
- Recall patterns by their trigger phrase: different → strategy, tell everyone → observer, behaves differently in a state → state, undo → command.
- Strategy is the workhorse: find the policy in the system and put it behind an interface.
- Observer needs per-listener error handling and a queue for slow listeners.
- Know adapter, decorator and facade apart; your main class is usually a facade already.
- Requirement first, pattern second — and choosing not to use one shows judgement.