Case study · Core

Design a Vending Machine

Select a product, insert coins, dispense the item, return change. The textbook use-case for modelling behaviour as a STATE machine instead of a tangle of flags.

Asked atAmazonMicrosoftFlipkart
step 1 / 8
1/2States as classes
current
VendingMachine
- state: VMState
+ insertCoin()
+ select(p)
«interface»
VMState
+ insertCoin()
+ select(p)
+ dispense()
Inventory
- slots: Map
IdleState
HasMoney
Dispensing
States as classes
1interface VMState { void insertCoin(Coin c); void select(Product p); }
2class IdleState implements VMState { ... }
3class HasMoney implements VMState { ... }
4class Dispensing implements VMState { ... }
5class VendingMachine { VMState state; void insertCoin(c){ state.insertCoin(c); } }
State
VendingMachinedelegates to state

VendingMachine is the Context. It holds its CURRENT VMState and delegates every button press and coin straight to it — no flags of its own. Inventory just maps slots to products.