LLD: vending machine with the State pattern
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer inserts Rs 15 and presses select. What happens depends on what the machine is doing right now: waiting, holding money, dropping an item or empty. The same button must give a different, safe answer each time.
Requirements: select item, insert coins, dispense, return change
The buttons are few, but the edge cases decide the design. This is the scope to agree on.
Coins: Rs 1, 2, 5, 10 accepted; anything else is returnedItems: code -> name, price, count (A1 Pen Rs 20, A2 Notebook Rs 25, B1 Eraser Rs 12)Flow: insert coins -> select item -> item and change come outCancel: returns all inserted money (before an item is chosen)Sold out: item stays selectable but says "sold out"; machine empty -> rejects coinsChange: from the coin box; if exact change is impossible, refuse the saleInvalid: select with no money, coins while dispensing -> rejected with a messageAsk which coins are accepted, what happens when an item is sold out, and what happens when the machine cannot give exact change.
The last one surprises many candidates: a machine with no Rs 1 coins cannot sell a Rs 14 item to someone who inserted Rs 15.
States: Idle, HasMoney, Dispensing, OutOfStock
The State pattern gives each state of an object its own class, and the object hands every request to its current state object.
Four state classes, and the same button presses handled differently by each.
Example 1 · The four states in action
interface State { default State insertCoin(int coin, Machine m) { System.out.println(" Rejected coin in " + this); return this; } default State select(Machine m) { System.out.println(" Rejected select in " + this); return this; } default State dispense(Machine m) { System.out.println(" Rejected dispense in " + this); return this; }}
class Idle implements State { public State insertCoin(int coin, Machine m) { m.balance += coin; return new HasMoney(); } public String toString() { return "Idle"; }}
class HasMoney implements State { public State insertCoin(int coin, Machine m) { m.balance += coin; return this; } public State select(Machine m) { if (m.balance < m.price) { System.out.println(" Need Rs " + (m.price - m.balance) + " more"); return this; } return new Dispensing(); } public String toString() { return "HasMoney"; }}
class Dispensing implements State { public State dispense(Machine m) { m.stock--; System.out.println(" Pen out, change Rs " + (m.balance - m.price)); m.balance = 0; return m.stock > 0 ? new Idle() : new OutOfStock(); } public String toString() { return "Dispensing"; }}
class OutOfStock implements State { public String toString() { return "OutOfStock"; }}
class Machine { State state = new Idle(); int balance, price = 20, stock = 1;
void press(String button, int coin) { System.out.println(button + " in " + state); state = switch (button) { case "coin" -> state.insertCoin(coin, this); case "select" -> state.select(this); default -> state.dispense(this); }; }}
public class VendingStatesDemo { public static void main(String[] args) { Machine m = new Machine(); m.press("select", 0); m.press("coin", 10); m.press("select", 0); m.press("coin", 10); m.press("select", 0); m.press("coin", 5); m.press("dispense", 0); m.press("coin", 10); System.out.println("Final state: " + m.state); }}select in Idle Rejected select in Idle coin in Idle select in HasMoney Need Rs 10 more coin in HasMoney select in HasMoney coin in Dispensing Rejected coin in Dispensing dispense in Dispensing Pen out, change Rs 0 coin in OutOfStock Rejected coin in OutOfStock Final state: OutOfStock
What this code does
- Each button is passed to the current state object, and the state returns the next state. The machine itself has no
ifon its status. - "select" means three different things here: rejected in
Idle, "need Rs 10 more" inHasMoneywith Rs 10, and a move toDispensingwith Rs 20. - A coin while
Dispensingis rejected by the interface's default method; after the last packet, the coin inOutOfStockis rejected too.
The machine has a State field; pressing a button calls state.select(machine, code); the state does the right thing and may switch the machine to another state. The four states are Idle (waiting for money), HasMoney (coins inserted), Dispensing (an item is coming out) and OutOfStock (nothing left to sell).
Without the pattern, every button method grows an if or switch over a status field, and a new state means editing all of them. The moves between states:
- Idle --coin--> HasMoney
- HasMoney --coin--> HasMoney (balance grows); --cancel--> Idle (money back)
- HasMoney --select, enough money, change possible--> Dispensing
- Dispensing --done--> Idle, or OutOfStock when the last item is gone
Inventory and change calculation
Greedy change gives as many of the biggest coin as possible, then the next, and so on, never using more coins than the box holds.
Change is paid out of a limited coin box, biggest coins first.
Example 2 · Change from a limited coin box
import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;
class CoinBox { private final TreeMap<Integer, Integer> coins = new TreeMap<>(Comparator.reverseOrder());
void add(int coin, int count) { coins.merge(coin, count, Integer::sum); }
// greedy: biggest coins first, never more than the box holds Optional<List<Integer>> change(int amount) { List<Integer> out = new ArrayList<>(); for (Map.Entry<Integer, Integer> e : coins.entrySet()) { int use = Math.min(amount / e.getKey(), e.getValue()); for (int i = 0; i < use; i++) out.add(e.getKey()); amount -= use * e.getKey(); } return amount == 0 ? Optional.of(out) : Optional.empty(); }
public String toString() { return coins.toString(); }}
public class ChangeDemo { public static void main(String[] args) { CoinBox box = new CoinBox(); box.add(10, 2); box.add(5, 1); box.add(2, 3); System.out.println("Box: " + box); for (int amount : new int[] {17, 9, 6, 1}) { System.out.println("Change for Rs " + amount + ": " + box.change(amount).map(Object::toString).orElse("not possible")); } }}Box: {10=2, 5=1, 2=3}
Change for Rs 17: [10, 5, 2]
Change for Rs 9: [5, 2, 2]
Change for Rs 6: not possible
Change for Rs 1: not possibleWhat this code does
- A
TreeMapwithComparator.reverseOrder()keeps coins from biggest to smallest, which is the order greedy needs. - Rs 17 (10 + 5 + 2) and Rs 9 (5 + 2 + 2) work. Rs 1 fails because the box has no Rs 1 coin, so the machine must refuse a sale that needs it.
- Rs 6 fails too, even though 2 + 2 + 2 would work: greedy takes the Rs 5 first and gets stuck. That is the limit mentioned in the note above.
The inventory is the count of each item; the coin box is the count of each coin the machine holds. Coins inserted by users go into the box and change comes out of it, so the machine can run out of small coins.
If an amount is left when the coins run out, exact change is impossible and the sale must be refused before the item drops.
Trace the code
Pay change from a limited coin box
Step through the greedy rule: biggest coins first.
Variables
- coins
- {10, 5, 2, 1}
- have
- {2, 1, 1, 3}
- left
- 28
Output
(nothing printed yet)Line 5The coin box holds two Rs 10, one Rs 5, one Rs 2 and three Rs 1 coins. The change to pay is Rs 28.
Rejecting invalid actions per state
An invalid action is a button press that makes no sense in the current state, such as select in Idle. The machine refuses it with a message and stays in the same state.
First a bug that lets a free item out, then the State version that rejects the same presses.
Example 3 · Bug: status flags let a free item out
class FlagMachine { boolean hasMoney; boolean dispensing; int balance; int price = 20;
void insertCoin(int coin) { balance += coin; hasMoney = true; }
void select() { if (hasMoney && balance >= price) dispensing = true; else System.out.println(" Not enough money"); }
void dispense() { // forgot to check 'dispensing' here System.out.println(" Item out! balance was Rs " + balance); balance = 0; hasMoney = false; dispensing = false; }}
public class FlagBugDemo { public static void main(String[] args) { FlagMachine m = new FlagMachine(); System.out.println("Press dispense with no money:"); m.dispense(); System.out.println("Insert Rs 5, press select, then dispense:"); m.insertCoin(5); m.select(); m.dispense(); }}Press dispense with no money: Item out! balance was Rs 0 Insert Rs 5, press select, then dispense: Not enough money Item out! balance was Rs 5
What this code does
- With two booleans and a balance, every method must check the right combination. One forgotten check in
dispensegives items away for free. - The flags can also disagree (for example
dispensingtrue whilehasMoneyis false), and nothing stops that. - The next example sends the same presses to the State pattern machine, where
dispenseoutsideDispensingis rejected by default.
Example 4 · The State machine rejects the same presses
import java.util.ArrayList;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;
record Item(String name, int price) { }
interface State { String name(); default void insertCoin(VendingMachine m, int coin) { m.reject("insert a coin", this); } default void select(VendingMachine m, String code) { m.reject("select an item", this); } default void dispense(VendingMachine m) { m.reject("dispense", this); } default void cancel(VendingMachine m) { m.reject("cancel", this); }}
class IdleState implements State { public String name() { return "Idle"; } public void insertCoin(VendingMachine m, int coin) { if (m.acceptCoin(coin)) m.setState(m.hasMoney); }}
class HasMoneyState implements State { public String name() { return "HasMoney"; } public void insertCoin(VendingMachine m, int coin) { m.acceptCoin(coin); } public void select(VendingMachine m, String code) { Item item = m.item(code); if (item == null) { m.log("Unknown item " + code); return; } if (m.stock(code) == 0) { m.log(item.name() + " is sold out"); return; } if (m.balance() < item.price()) { m.log("Insert Rs " + (item.price() - m.balance()) + " more for " + item.name()); return; } if (m.makeChange(m.balance() - item.price()).isEmpty()) { m.log("No change for Rs " + (m.balance() - item.price()) + ", pick another item or cancel"); return; } m.choose(code); m.setState(m.dispensing); m.dispense(); } public void cancel(VendingMachine m) { m.log("Returned Rs " + m.balance()); m.refund(); m.setState(m.idle); }}
class DispensingState implements State { public String name() { return "Dispensing"; } public void dispense(VendingMachine m) { m.release(); m.setState(m.anyStock() ? m.idle : m.outOfStock); }}
class OutOfStockState implements State { public String name() { return "OutOfStock"; } public void insertCoin(VendingMachine m, int coin) { m.log("Machine empty, returned Rs " + coin); }}
class VendingMachine { final State idle = new IdleState(), hasMoney = new HasMoneyState(); final State dispensing = new DispensingState(), outOfStock = new OutOfStockState(); private State state = idle; private int balance; private String chosen; private final List<Integer> inserted = new ArrayList<>(); private final Map<String, Item> items = new LinkedHashMap<>(); private final Map<String, Integer> stock = new HashMap<>(); private final TreeMap<Integer, Integer> coinBox = new TreeMap<>(Comparator.reverseOrder());
void load(String code, Item item, int count) { items.put(code, item); stock.put(code, count); } void loadCoins(int coin, int count) { coinBox.merge(coin, count, Integer::sum); }
// the public buttons: each one is handed to the current state void insertCoin(int coin) { state.insertCoin(this, coin); } void select(String code) { state.select(this, code); } void dispense() { state.dispense(this); } void cancel() { state.cancel(this); }
void setState(State next) { state = next; } String stateName() { return state.name(); } void log(String text) { System.out.println(" " + text); } void reject(String action, State s) { log("Rejected: cannot " + action + " while " + s.name()); }
boolean acceptCoin(int coin) { if (coin != 1 && coin != 2 && coin != 5 && coin != 10) { log("Rejected coin Rs " + coin); return false; } balance += coin; inserted.add(coin); coinBox.merge(coin, 1, Integer::sum); log("Balance Rs " + balance); return true; }
Optional<List<Integer>> makeChange(int amount) { List<Integer> coins = new ArrayList<>(); for (Map.Entry<Integer, Integer> e : coinBox.entrySet()) { int use = Math.min(amount / e.getKey(), e.getValue()); for (int i = 0; i < use; i++) coins.add(e.getKey()); amount -= use * e.getKey(); } return amount == 0 ? Optional.of(coins) : Optional.empty(); }
void release() { Item item = items.get(chosen); List<Integer> change = makeChange(balance - item.price()).orElseThrow(); change.forEach(c -> coinBox.merge(c, -1, Integer::sum)); stock.merge(chosen, -1, Integer::sum); log("Dispensed " + item.name() + (change.isEmpty() ? "" : ", change " + change)); balance = 0; inserted.clear(); chosen = null; }
Item item(String code) { return items.get(code); } int stock(String code) { return stock.getOrDefault(code, 0); } int balance() { return balance; } void refund() { // the inserted coins go back out of the box inserted.forEach(c -> coinBox.merge(c, -1, Integer::sum)); inserted.clear(); balance = 0; } void choose(String code) { chosen = code; } boolean anyStock() { return stock.values().stream().anyMatch(n -> n > 0); }}
public class RejectInvalidDemo { public static void main(String[] args) { VendingMachine m = new VendingMachine(); m.load("A1", new Item("Pen", 20), 2); System.out.println("dispense in " + m.stateName() + ":"); m.dispense(); System.out.println("select in " + m.stateName() + ":"); m.select("A1"); System.out.println("cancel in " + m.stateName() + ":"); m.cancel(); System.out.println("coin Rs 5 in " + m.stateName() + ":"); m.insertCoin(5); System.out.println("select A1 in " + m.stateName() + ":"); m.select("A1"); System.out.println("dispense in " + m.stateName() + ":"); m.dispense(); System.out.println("Still in " + m.stateName() + " with Rs " + m.balance()); }}dispense in Idle: Rejected: cannot dispense while Idle select in Idle: Rejected: cannot select an item while Idle cancel in Idle: Rejected: cannot cancel while Idle coin Rs 5 in Idle: Balance Rs 5 select A1 in HasMoney: Insert Rs 15 more for Pen dispense in HasMoney: Rejected: cannot dispense while HasMoney Still in HasMoney with Rs 5
What this code does
Idleoverrides onlyinsertCoin, so dispense, select and cancel all fall back to the interface's rejectingdefaultmethods.- With Rs 5 the machine is in
HasMoney: select explains what is missing, and dispense is still rejected because onlyDispensingmay release an item. - Every rejection leaves the state and balance unchanged, which is exactly what "reject an invalid action" means.
In the State pattern this is almost free: the State interface gives every action a default method that rejects it, and each state class overrides only the actions that are valid for it.
A forgotten case is then a safe rejection, not a free item.
Fix the error
Override the interface method
Read the real compiler error, then pick the line that fixes it.
HasMoneyState must handle select.
Error
HasMoneyState.java:6: error: select(String) in HasMoneyState cannot implement select(String) in State
void select(String code) {
^
attempting to assign weaker access privileges; was publicSingle-file design with a demo run
The context is the object whose behaviour changes with its state, here VendingMachine. It holds the current state and hands each request to it.
A normal purchase with change, an invalid press, a refused sale, a cancel, and the last item.
Example 5 · The vending machine in one file
import java.util.ArrayList;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;
record Item(String name, int price) { }
interface State { String name(); default void insertCoin(VendingMachine m, int coin) { m.reject("insert a coin", this); } default void select(VendingMachine m, String code) { m.reject("select an item", this); } default void dispense(VendingMachine m) { m.reject("dispense", this); } default void cancel(VendingMachine m) { m.reject("cancel", this); }}
class IdleState implements State { public String name() { return "Idle"; } public void insertCoin(VendingMachine m, int coin) { if (m.acceptCoin(coin)) m.setState(m.hasMoney); }}
class HasMoneyState implements State { public String name() { return "HasMoney"; } public void insertCoin(VendingMachine m, int coin) { m.acceptCoin(coin); } public void select(VendingMachine m, String code) { Item item = m.item(code); if (item == null) { m.log("Unknown item " + code); return; } if (m.stock(code) == 0) { m.log(item.name() + " is sold out"); return; } if (m.balance() < item.price()) { m.log("Insert Rs " + (item.price() - m.balance()) + " more for " + item.name()); return; } if (m.makeChange(m.balance() - item.price()).isEmpty()) { m.log("No change for Rs " + (m.balance() - item.price()) + ", pick another item or cancel"); return; } m.choose(code); m.setState(m.dispensing); m.dispense(); } public void cancel(VendingMachine m) { m.log("Returned Rs " + m.balance()); m.refund(); m.setState(m.idle); }}
class DispensingState implements State { public String name() { return "Dispensing"; } public void dispense(VendingMachine m) { m.release(); m.setState(m.anyStock() ? m.idle : m.outOfStock); }}
class OutOfStockState implements State { public String name() { return "OutOfStock"; } public void insertCoin(VendingMachine m, int coin) { m.log("Machine empty, returned Rs " + coin); }}
class VendingMachine { final State idle = new IdleState(), hasMoney = new HasMoneyState(); final State dispensing = new DispensingState(), outOfStock = new OutOfStockState(); private State state = idle; private int balance; private String chosen; private final List<Integer> inserted = new ArrayList<>(); private final Map<String, Item> items = new LinkedHashMap<>(); private final Map<String, Integer> stock = new HashMap<>(); private final TreeMap<Integer, Integer> coinBox = new TreeMap<>(Comparator.reverseOrder());
void load(String code, Item item, int count) { items.put(code, item); stock.put(code, count); } void loadCoins(int coin, int count) { coinBox.merge(coin, count, Integer::sum); }
// the public buttons: each one is handed to the current state void insertCoin(int coin) { state.insertCoin(this, coin); } void select(String code) { state.select(this, code); } void dispense() { state.dispense(this); } void cancel() { state.cancel(this); }
void setState(State next) { state = next; } String stateName() { return state.name(); } void log(String text) { System.out.println(" " + text); } void reject(String action, State s) { log("Rejected: cannot " + action + " while " + s.name()); }
boolean acceptCoin(int coin) { if (coin != 1 && coin != 2 && coin != 5 && coin != 10) { log("Rejected coin Rs " + coin); return false; } balance += coin; inserted.add(coin); coinBox.merge(coin, 1, Integer::sum); log("Balance Rs " + balance); return true; }
Optional<List<Integer>> makeChange(int amount) { List<Integer> coins = new ArrayList<>(); for (Map.Entry<Integer, Integer> e : coinBox.entrySet()) { int use = Math.min(amount / e.getKey(), e.getValue()); for (int i = 0; i < use; i++) coins.add(e.getKey()); amount -= use * e.getKey(); } return amount == 0 ? Optional.of(coins) : Optional.empty(); }
void release() { Item item = items.get(chosen); List<Integer> change = makeChange(balance - item.price()).orElseThrow(); change.forEach(c -> coinBox.merge(c, -1, Integer::sum)); stock.merge(chosen, -1, Integer::sum); log("Dispensed " + item.name() + (change.isEmpty() ? "" : ", change " + change)); balance = 0; inserted.clear(); chosen = null; }
Item item(String code) { return items.get(code); } int stock(String code) { return stock.getOrDefault(code, 0); } int balance() { return balance; } void refund() { // the inserted coins go back out of the box inserted.forEach(c -> coinBox.merge(c, -1, Integer::sum)); inserted.clear(); balance = 0; } void choose(String code) { chosen = code; } boolean anyStock() { return stock.values().stream().anyMatch(n -> n > 0); }}
public class VendingMachineDemo { static void step(VendingMachine m, String label, Runnable action) { System.out.println(label + " [" + m.stateName() + "]"); action.run(); }
public static void main(String[] args) { VendingMachine m = new VendingMachine(); m.load("A1", new Item("Pen", 20), 1); m.load("B1", new Item("Eraser", 12), 1); m.loadCoins(5, 1); m.loadCoins(2, 2);
step(m, "Asha inserts Rs 10, Rs 10, Rs 5", () -> { m.insertCoin(10); m.insertCoin(10); m.insertCoin(5); }); step(m, "Asha selects A1", () -> m.select("A1")); step(m, "Ravi inserts Rs 3", () -> m.insertCoin(3)); step(m, "Ravi inserts Rs 10, Rs 5", () -> { m.insertCoin(10); m.insertCoin(5); }); step(m, "Ravi selects A1", () -> m.select("A1")); step(m, "Ravi selects B1", () -> m.select("B1")); step(m, "Ravi cancels", m::cancel); step(m, "Meera inserts Rs 10, Rs 2", () -> { m.insertCoin(10); m.insertCoin(2); }); step(m, "Meera selects B1", () -> m.select("B1")); step(m, "John inserts Rs 10", () -> m.insertCoin(10)); System.out.println("Final state: " + m.stateName()); }}Asha inserts Rs 10, Rs 10, Rs 5 [Idle] Balance Rs 10 Balance Rs 20 Balance Rs 25 Asha selects A1 [HasMoney] Dispensed Pen, change [5] Ravi inserts Rs 3 [Idle] Rejected coin Rs 3 Ravi inserts Rs 10, Rs 5 [Idle] Balance Rs 10 Balance Rs 15 Ravi selects A1 [HasMoney] Pen is sold out Ravi selects B1 [HasMoney] No change for Rs 3, pick another item or cancel Ravi cancels [HasMoney] Returned Rs 15 Meera inserts Rs 10, Rs 2 [Idle] Balance Rs 10 Balance Rs 12 Meera selects B1 [HasMoney] Dispensed Eraser John inserts Rs 10 [OutOfStock] Machine empty, returned Rs 10 Final state: OutOfStock
What this code does
- Asha pays Rs 25 for Rs 20 chips and gets a Rs 5 coin back from the box. A Rs 3 coin is not accepted, so Ravi stays in
Idle. - Ravi's Rs 15 cannot buy the sold-out pen, and the box has no Rs 1 coin, so it cannot make Rs 3 change for biscuits, so he cancels and gets his money back.
- Meera buys the last item with exact money, the machine moves to
OutOfStock, and John's coin is returned.
The single-file design has the State interface, four state classes, an Item record and VendingMachine, which holds the current state, balance, inventory and coin box. Each public button method is one line: hand the request to the current state.
The demo ends by selling the last item, so the machine moves to OutOfStock.
Next step
Check your understanding
12 quick questions