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:
- IdleState: Waiting for money.
- ReadyState: Money inserted, waiting for selection.
- DispenseState: Product being released.
- 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.