Back to LLD explorer
State Pattern / Behavioral Patterns: State

Vending Machine

Easy

Problem Summary

Design a Vending Machine that transitions cleanly between states: Idle, Waiting for Coins, Dispensing, Out of Stock.

Functional Scope

  • Display items with prices and quantities.
  • Accept coins/cash inputs, calculate balance, and return change.
  • Ensure transaction safety: don't release items unless funds are confirmed.

Entity-Relationship (ER) Schema

VendingMachine [1] <---> [1] State
VendingMachine [1] <---> [1] Inventory
Inventory [1] <---> [*] Product

Design Approach

Use the State pattern to represent machine phases. The context object (VendingMachine) delegates all action calls to the current state object, which controls state changes based on logic rules.

Core Classes & Models

VendingMachine (Context class)State (Interface with selectProduct, insertCoin, pressButton, dispense)IdleState, HasMoneyState, DispensingState, SoldOutState (Concrete states)Inventory & Product
Code Blueprint
public interface State {
    void insertCoin(VendingMachine m, double amt);
    void selectProduct(VendingMachine m, String code);
}