Skip to main content
← CONCEPTS / DESIGN PATTERNS
An end-to-end domain learning journey

Core LLD Behavioral Patterns: State,
Strategy & Observer in Practice.

Behavioral patterns—State, Strategy, and Observer—eliminate brittle if-else chains in Low-Level Design interviews and production systems by encapsulating lifecycle transitions, interchangeable algorithms, and event notifications behind clean interfaces.
Start the journey7 sections· Last modified Nov 16, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

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 State object representing its current lifecycle phase; transitions happen inside states as actions occur.
  • Strategy: Context delegates an algorithm (e.g., pricing, routing) to an injected Strategy interface that can be swapped without changing lifecycle.
State Pattern Lifecycle

Vending Machine State Transitions

insertCoin()selectItem()dispenseComplete()IDLEAwaiting coinHAS MONEYSelect itemDISPENSINGRelease + change

Each concrete State class handles valid actions for that phase and rejects invalid ones (e.g., dispense() while IDLE).

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

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.

Pattern Collaboration

Parking Lot Exit: Strategy Fee + State Release + Observer Board

ExitGatePricingStrategySpotStateDisplayObserver1. calculateFee(ticket)2. release() -> AVAILABLE3. notify(freeCount + 1)

Strategy computes the fee, State transitions the spot, and Observer updates display boards without tight coupling.

Engineering Decision Framework
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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

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.

Request & State Flow

Mapping real-world LLD entities to the right pattern

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
ChoiceWhat it buysWhat it costs
State Pattern: LifecyclesVending machines, order workflows, elevator door/motion states.Adds a class per state; overkill for a simple 2-state boolean toggle.
Strategy Pattern: AlgorithmsParking fee rules, elevator dispatch (SCAN vs Nearest), payment gateways.Callers or a Factory must resolve the right strategy key.
Observer Pattern: Event Fan-OutDisplay boards, inventory alerts, audit loggers decoupled from the core entity.Unbounded or forgotten listeners cause memory leaks.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

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);
    }
}
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

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.

Component Topology

Alternatives: Pattern Classes vs. Enum State Machines vs. Event Bus

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
ChoiceWhat it buysWhat it costs
Concrete State ClassesFull polymorphism and Open/Closed extensibility per state.More files/boilerplate for trivial 2-state machines.
Java Enum with Abstract MethodsCompact, 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 ObserverAsync bus prevents slow observers from blocking the core transaction.Introduces eventual consistency and ordering considerations.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

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).

Design Trade-Off

Avoiding Singleton State Corruption & Observer Leaks

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • 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.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

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?

Recommended Learning Flow