Design a Vending Machine

Medium
State MachinesStateSingleton

Problem Statement

Design a vending machine that:

  • Holds different products with prices and quantities
  • Accepts coins/bills as payment
  • Dispenses products and returns change
  • Has clear state transitions

Design Requirements

The vending machine has 4 states:

  1. Idle — Waiting for user input
  2. HasMoney — Money inserted, waiting for product selection
  3. Dispensing — Product selected, dispensing
  4. OutOfStock — Selected product is unavailable

Key Behaviors:

  • insertMoney(amount) — Insert coins/bills
  • selectProduct(productCode) — Choose a product
  • dispenseProduct() — Give out product and change
  • cancelTransaction() — Return inserted money

!Constraints

- Accepts denominations: $0.25, $0.50, $1.00, $5.00, $10.00, $20.00 - Products have a price, name, and quantity - Must give exact change (or reject if unable to) - State transitions must be enforced — can't select product before inserting money - Machine can hold up to 10 distinct products, 20 units each
Output

Run your code to see output here.