Skip to content

LLD Quick Revision Guide

Use this page the night before an interview. Each section is a summary with a link to the full page.

StepTimeWhat to do
1. Clarify5 minAsk for functional requirements, scale, actors, constraints; fix the scope out loud.
2. Entities5 minList nouns → classes/enums; verbs → methods.
3. Relationships5 minDraw the class diagram: association, aggregation, composition, inheritance.
4. APIs5 minDefine the public interfaces/methods first, implementation later.
5. Patterns5 minApply patterns only where a real variation exists (Strategy, State, Observer…).
6. Code15 minWrite core classes and the main flow; keep it compilable.
7. Extend5 minShow how new requirements plug in (OCP), then discuss concurrency.
  • Requirements confirmed and scoped (what is out of scope?).
  • Enums for fixed sets (status, type, level).
  • Interfaces for things that vary (payment, pricing, notification).
  • Single responsibility per class; manager/service classes orchestrate.
  • Thread safety on shared state (inventory, seats, slots, balances).
  • Custom exceptions for domain errors (InsufficientBalanceException).
  • Mention testing, extensibility and what you would improve.
PillarMeaningJava cue
EncapsulationHide state, expose behaviourprivate fields + getters/methods
AbstractionExpose what, hide howinterface, abstract class
Inheritanceis-a reuseextends
PolymorphismSame call, different behaviouroverriding, interface references

More: Object-Oriented Analysis and Design.

PrincipleOne-linerViolation smellFix
Single ResponsibilityA class has one reason to changeInvoice that calculates, prints and savesSplit into InvoiceCalculator, InvoicePrinter, InvoiceRepository
Open/ClosedOpen for extension, closed for modificationif/else or switch on typeInterface + new implementation (Strategy/Factory)
Liskov SubstitutionSubtypes must be usable as their base typeSubclass throws UnsupportedOperationExceptionBetter hierarchy, split interfaces
Interface SegregationMany small interfaces beat one fat oneImplementers leave methods emptySplit Worker into Workable, Eatable
Dependency InversionDepend on abstractions, not concretionsnew MySqlRepo() inside a serviceInject an interface via constructor
OCP + DIP together
interface PaymentMethod { void pay(double amount); }
class CardPayment implements PaymentMethod { public void pay(double a) { /* ... */ } }
class UpiPayment implements PaymentMethod { public void pay(double a) { /* ... */ } }
class Checkout {
private final PaymentMethod method; // depends on abstraction
Checkout(PaymentMethod method) { this.method = method; } // injected
void complete(double amount) { method.pay(amount); }
}

More: S.O.L.I.D. Principles.

RelationshipMeaningLifetimeArrowJava cue
Dependencyuses temporarilynonedashed →parameter / local variable
Associationknowsindependentsolid linefield reference
Aggregationhas-a (weak)part can outlive wholehollow ◇field set from outside
Compositionowns (strong)part dies with wholefilled ◆new inside constructor
Inheritanceis-an/ahollow ▷ solidextends
Realizationimplements interfacen/ahollow ▷ dashedimplements
PatternIntentUse whenLLD example
SingletonOne instance, global accessshared config, logger, cache managerLogger, ParkingLot
Factory Method / Simple FactoryCreate objects without exposing the classtype chosen at runtimeVehicle, Notification, Shape
Abstract FactoryFamilies of related objectsUI theme, cross-platform widgetsGUI kits
BuilderStep-by-step constructionmany optional fieldsPizza, HttpRequest
PrototypeClone existing objectcreation is costlygame objects
Thread-safe Singleton (enum)
public enum Config {
INSTANCE;
public String get(String key) { return System.getProperty(key); }
}
Builder
class Pizza {
private final String size; private final boolean cheese; private final boolean olives;
private Pizza(Builder b) { size = b.size; cheese = b.cheese; olives = b.olives; }
static class Builder {
private String size; private boolean cheese, olives;
Builder size(String s) { this.size = s; return this; }
Builder cheese(boolean c) { this.cheese = c; return this; }
Builder olives(boolean o) { this.olives = o; return this; }
Pizza build() { return new Pizza(this); }
}
}
// new Pizza.Builder().size("L").cheese(true).build();

More: Creational patterns.

PatternIntentUse whenExample
AdapterConvert one interface to anotherintegrate legacy/third-party APIpayment gateway wrapper
BridgeDecouple abstraction from implementationtwo independent dimensionsShape × Renderer
CompositeTreat tree of objects uniformlypart-whole hierarchyfile system, menu
DecoratorAdd behaviour dynamicallyoptional stackable featurestoppings, coffee add-ons
FacadeSimple API over complex subsystemmany collaboratorsOrderService, checkout
FlyweightShare intrinsic statehuge number of similar objectstext characters, trees
ProxyControl accesslazy load, auth, cache, remotecached image loader
Decorator
interface Coffee { double cost(); }
class Espresso implements Coffee { public double cost() { return 50; } }
abstract class CoffeeDecorator implements Coffee {
protected final Coffee inner;
CoffeeDecorator(Coffee inner) { this.inner = inner; }
}
class Milk extends CoffeeDecorator {
Milk(Coffee c) { super(c); }
public double cost() { return inner.cost() + 10; }
}
// new Milk(new Milk(new Espresso())).cost() -> 70

More: Structural patterns.

PatternIntentUse whenLLD example
StrategySwap algorithms at runtimeif/else over algorithm typepricing, payment, sorting, parking fee
ObserverNotify dependents of changesone-to-many eventsnotifications, stock ticker
StateBehaviour changes with statefinite-state machinevending machine, ATM, elevator, order status
CommandWrap request as objectundo/redo, queuestext editor, remote control
Template MethodFixed skeleton, variable stepssame flow with different stepsdata import/export
Chain of ResponsibilityPass request along handlersmultiple possible handlerslogging levels, approvals, ATM cash dispense
IteratorTraverse without exposing structurecustom collectionstree/graph iteration
MediatorCentralise communicationmany-to-many interactionchat room, air traffic
MementoSave/restore stateundoeditor snapshots
VisitorNew operation without changing classesstable hierarchy, many operationsAST, tax calculation
Strategy
interface PricingStrategy { double fee(long minutes); }
class HourlyPricing implements PricingStrategy {
public double fee(long m) { return Math.ceil(m / 60.0) * 20; }
}
class FlatPricing implements PricingStrategy {
public double fee(long m) { return 100; }
}
class Ticket {
private PricingStrategy strategy;
Ticket(PricingStrategy s) { this.strategy = s; }
void setStrategy(PricingStrategy s) { this.strategy = s; }
double bill(long minutes) { return strategy.fee(minutes); }
}
Observer
interface Observer { void update(String event); }
class Subject {
private final List<Observer> observers = new ArrayList<>();
void subscribe(Observer o) { observers.add(o); }
void unsubscribe(Observer o) { observers.remove(o); }
void notifyAll(String event) { for (Observer o : observers) o.update(event); }
}
class EmailNotifier implements Observer {
public void update(String e) { System.out.println("Email: " + e); }
}
class Stock extends Subject {
void setPrice(double p) {
notifyAll("Price changed to " + p);
}
}
State
interface State { void next(Order o); String name(); }
class Placed implements State {
public void next(Order o) { o.setState(new Shipped()); }
public String name() { return "PLACED"; }
}
class Shipped implements State {
public void next(Order o) { o.setState(new Delivered()); }
public String name() { return "SHIPPED"; }
}
class Delivered implements State {
public void next(Order o) { throw new IllegalStateException("Already delivered"); }
public String name() { return "DELIVERED"; }
}
class Order {
private State state = new Placed();
void setState(State s) { this.state = s; }
void next() { state.next(this); }
}
Command (with undo)
interface Command { void execute(); void undo(); }
class AddText implements Command {
private final Editor e; private final String text;
AddText(Editor e, String t) { this.e = e; this.text = t; }
public void execute() { e.append(text); }
public void undo() { e.delete(text.length()); }
}
class Invoker {
private final Deque<Command> history = new ArrayDeque<>();
void run(Command c) { c.execute(); history.push(c); }
void undo() { if (!history.isEmpty()) history.pop().undo(); }
}

More: Behavioural patterns.

NeedJava toolNote
Mutual exclusion on a method/blocksynchronizedsimple, coarse
Fine-grained / try-lock / timeoutReentrantLockalways unlock in finally
Many readers, few writersReentrantReadWriteLockcache, config
Thread-safe mapConcurrentHashMapatomic ops: compute, merge, putIfAbsent
CountersAtomicInteger/LongCAS, lock-free
Producer/consumerBlockingQueuedecouples threads
Async tasksExecutorServicedo not spawn raw threads
Visibility flagvolatileno atomicity
Book a seat safely
class Show {
private final Map<Integer, Boolean> seats = new HashMap<>();
public synchronized boolean book(int seatNo) {
if (Boolean.TRUE.equals(seats.get(seatNo))) return false; // already booked
seats.put(seatNo, true);
return true;
}
}

Acquire locks in a fixed global order (e.g. by account id when transferring money) and prefer tryLock with timeout.

SystemKey entitiesPatterns / concepts
Parking LotVehicle, Slot, Ticket, GateStrategy (pricing, slot allocation), Factory (vehicle), Singleton
ElevatorElevator, Request, ControllerState, Strategy (scheduling), Observer
ATMCard, Account, Cash dispenserState, Chain of Responsibility (notes)
LRU CacheHashMap + doubly linked listData structures, thread safety, Strategy (eviction)
Logging SystemLogger, Appender, LevelSingleton, Chain of Responsibility, Strategy
Movie Ticket BookingShow, Seat, BookingConcurrency (seat lock), Strategy (payment), Observer
Hotel BookingRoom, ReservationStrategy (pricing), State, concurrency
Car RentalVehicle, Reservation, PaymentFactory, Strategy, State
Library ManagementBook, Member, LoanObserver (due reminders), Factory
Online ShoppingCart, Order, PaymentStrategy, Observer, State (order), Facade
Snake and LadderBoard, Dice, PlayerStrategy (dice), simple OOP
Payment GatewayTransaction, Processor, FraudStrategy, Adapter, State, Chain of Responsibility
  • Entities, enums and interfaces are clearly named.
  • Every pattern you used solves a stated problem.
  • Core flow is walked through with an example (happy path + one failure).
  • Shared state is protected (locks / concurrent collections).
  • You explained extensibility: “to add X, I add a new class implementing Y; nothing else changes.”
  • You mentioned trade-offs and what you would add with more time (persistence, monitoring, caching).