Lesson 10 of 17 2 min

LLD Masterclass: Designing a Vending Machine

Learn how to model finite state machines for physical device LLD interviews.

1. Requirements (The Scope)

  • Functional:
    • Accept coins/cash.
    • Select a product.
    • Dispense product and return change.
    • Handle "Out of Stock" and "Insufficient Funds."
  • Non-Functional:
    • Predictable state transitions.
    • Extensible to new payment types (Card/NFC).

2. The Core Pattern: Finite State Machine (FSM)

A Vending Machine is a classic example of an FSM. It is always in exactly one of several states.

The States:

  1. IdleState: Waiting for money.
  2. ReadyState: Money inserted, waiting for selection.
  3. DispenseState: Product being released.
  4. OutOfServiceState: Maintenance mode.

3. Java Implementation (Simplified)

public interface VendingState {
    void insertCoin(VendingMachine machine, double amount);
    void selectProduct(VendingMachine machine, String productId);
    void dispense(VendingMachine machine);
}

public class IdleState implements VendingState {
    @Override
    public void insertCoin(VendingMachine machine, double amount) {
        machine.addBalance(amount);
        machine.setState(new ReadyState());
    }
    // ...
}

4. Key Entities

  • VendingMachine: Context object holding current state and inventory.
  • Inventory: Managing product slots and quantities.
  • Product: Item with price and ID.
  • CoinSlot: Payment hardware interface.

Final Takeaway

When you see a system with clear "Modes" of operation, use the State Pattern. It prevents the "If-Else Nightmare" and makes your LLD interview code look professional and staff-level.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.