When a single bottleneck threatens end-to-end availability, Strategy & Observer in, use State when behavior changes with an object's internal lifecycle (Vending Machine, Order), Strategy when algorithms vary independently (Pricing, Dispatch), and Observer when decoupled listeners react to state changes.
TL;DR30-second simplified summary▾
Core Mechanics: Although State and Strategy share nearly identical UML class diagrams, their intent is distinct: State: Context delegates to a State object representing its current lifecycle phase; transitions happen inside states as actions occur.
Visual & Structural Flow: Depicts Vending Machine State Transitions (IDLE -> HAS MONEY -> DISPENSING); Parking Lot Exit: Strategy Fee + State Release + Observer Board (ExitGate -> PricingStrategy -> SpotState -> DisplayObserver).
Trade-Offs & Production: Balance class proliferation against extensibility. Two production pitfalls trip up teams using behavioral patterns: storing instance-specific fields inside shared singleton State objects (causing cross-request race conditions).
Failure Modes & Application: See State, Strategy, and Observer applied end-to-end in classic object-oriented system design problems.
What are State, Strategy, and Observer.
Why this matters: The mechanism: understand how State, Strategy, and Observer works from first principles.
Although State and Strategy share nearly identical UML class diagrams, their intent is distinct:
- State: Context delegates to a
Stateobject representing its current lifecycle phase; transitions happen inside states as actions occur.
- Strategy: Context delegates an algorithm (e.g., pricing, routing) to an injected
Strategyinterface that can be swapped without changing lifecycle.
Vending Machine State Transitions
Each concrete State class handles valid actions for that phase and rejects invalid ones (e.g., dispense() while IDLE).
Why hardcoded switch/if-else chains fail the Open/Closed Principle.
Why this matters: The problem: see what breaks without Why hardcoded switch/if-else chains fail the Open/Closed Principle under real concurrency or scale.
In both LLD interviews and production codebases, requirements evolve: 'add weekend flat-rate pricing', 'add a Maintenance state', or 'notify an audit webhook on dispense'.
When all transitions and algorithms live in one giant switch(status) block, every new feature modifies tested core logic and risks breaking unrelated branches. Behavioral patterns isolate each new state, algorithm, or listener into its own cohesive class.
Parking Lot Exit: Strategy Fee + State Release + Observer Board
Strategy computes the fee, State transitions the spot, and Observer updates display boards without tight coupling.
- Problem
- How to implement Core LLD Behavioral Patterns: State, Strategy & Observer in Practice without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- When a single bottleneck threatens end-to-end availability, strategy & Observer in, use State when behavior changes with an object's internal lifecycle (Vending Machine, Order), Strategy when algorithms vary independently (Pricing, Dispatch), and Observer when decoupled listeners react to state changes.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Core LLD Behavioral Patterns: State, Strategy & Observer in Practice experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Mapping real-world LLD entities to the right pattern.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Mapping real-world LLD entities to the right pattern as the intuition layer for Core LLD Behavioral Patterns: State, Strategy & Observer in Practice: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Choose each pattern based on whether the axis of variation is lifecycle phase, interchangeable algorithm, or fan-out notification.
Mapping real-world LLD entities to the right pattern
| Choice | What it buys | What it costs |
|---|---|---|
| State Pattern: Lifecycles | Vending machines, order workflows, elevator door/motion states. | Adds a class per state; overkill for a simple 2-state boolean toggle. |
| Strategy Pattern: Algorithms | Parking fee rules, elevator dispatch (SCAN vs Nearest), payment gateways. | Callers or a Factory must resolve the right strategy key. |
| Observer Pattern: Event Fan-Out | Display boards, inventory alerts, audit loggers decoupled from the core entity. | Unbounded or forgotten listeners cause memory leaks. |
Clean Java interfaces for State, Strategy & Observer.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Think of Clean Java interfaces for State, Strategy & Observer as the intuition layer for Core LLD Behavioral Patterns: State, Strategy & Observer in Practice: Operational control: configure bounds, failure handling, and safe production defaults.
Keep State implementations stateless (no per-machine mutable fields if shared as singletons) and store listeners in CopyOnWriteArrayList for safe concurrent iteration.
public interface PricingStrategy {
long calculateCents(Ticket ticket);
}
public interface SpotState {
void occupy(ParkingSpot spot, Vehicle v);
void vacate(ParkingSpot spot);
}
public final class ParkingLotSubject {
private final java.util.List<AvailabilityObserver> observers =
new java.util.concurrent.CopyOnWriteArrayList<>();
public void subscribe(AvailabilityObserver obs) { observers.add(obs); }
public void unsubscribe(AvailabilityObserver obs) { observers.remove(obs); }
public void notifyChange(FloorEvent evt) {
for (var obs : observers) obs.onAvailabilityChanged(evt);
}
}
Alternatives: Pattern Classes vs. Enum State Machines vs. Event Bus.
Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Think of Alternatives: Pattern Classes vs. Enum State Machines vs. Event Bus as the intuition layer for Core LLD Behavioral Patterns: State, Strategy & Observer in Practice: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Balance class proliferation against extensibility.
Alternatives: Pattern Classes vs. Enum State Machines vs. Event Bus
| Choice | What it buys | What it costs |
|---|---|---|
| Concrete State Classes | Full polymorphism and Open/Closed extensibility per state. | More files/boilerplate for trivial 2-state machines. |
| Java Enum with Abstract Methods | Compact, singleton-safe, zero extra files for fixed small state sets. | Harder to inject external Spring/DI dependencies into enum constants. |
| Async Event Bus vs. Sync Observer | Async bus prevents slow observers from blocking the core transaction. | Introduces eventual consistency and ordering considerations. |
Avoiding Singleton State Corruption & Observer Leaks.
Why this matters: Production architecture: see how the components compose end to end under real load.
Think of Avoiding Singleton State Corruption & Observer Leaks as the intuition layer for Core LLD Behavioral Patterns: State, Strategy & Observer in Practice: Production architecture: see how the components compose end to end under real load.
Two production pitfalls trip up teams using behavioral patterns: storing instance-specific fields inside shared singleton State objects (causing cross-request race conditions), and registering short-lived UI/request observers without unsubscribe() (leaking memory).
Avoiding Singleton State Corruption & Observer Leaks
- No backpressure on spikes
- Implicit shared state
- Cascading tail latency
- Explicit capacity budgets
- Isolated failure domains
- Predictable p99 latency
Stateless Transitions
Pass the Context (ParkingSpot, VendingMachine) into every State method and mutate fields only on the Context.
Weak/Explicit Unsubscribe
Always pair subscribe() with deterministic unsubscribe() or AutoCloseable handles.
LLD Case Studies & Design Principle Deep Dives.
Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.
Think of LLD Case Studies & Design Principle Deep Dives as the intuition layer for Core LLD Behavioral Patterns: State, Strategy & Observer in Practice: Applied problems: connect these internals to concrete system design and debugging scenarios.
See State, Strategy, and Observer applied end-to-end in classic object-oriented system design problems.
Practice: Make the trade-off yourself.
In a Parking Lot LLD, which pattern best models hourly vs flat-rate weekend pricing, and which models a spot's Available -> Occupied -> Maintenance lifecycle?