LOW LEVEL DESIGN · MACHINE CODING · EASY · 2 OF 42

Design a Vending Machine: State Pattern Low-Level Design in Java

The classic State pattern question: requirements, entities, why nested if statements break down, the Idle, HasMoney and Maintenance states with a transition table, the purchase flow, making change from a limited coin box (greedy, and when you need dynamic programming), restocking, low-stock alerts with Observer, thread safety and the follow-ups, with a full Java 17 solution.

Patterns usedObserverStateStrategySingleton

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 17

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 202 lines, with a small main() demo. Save it as VendingMachine.java, then run javac VendingMachine.java && java VendingMachine.

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** A vending machine as a state machine: the Idle, HasMoney and Maintenance states decide each button. */
public class VendingMachine {

    // ---------- the model ----------
    enum Coin {
        FIVE(5), TEN(10), TWENTY(20), FIFTY(50), HUNDRED(100);

        final int cents;

        Coin(int cents) { this.cents = cents; }
    }

    record Product(String name, int priceCents) {}

    static final class Slot {
        final String code;
        final Product product;
        int count;

        Slot(String code, Product product, int count) {
            this.code = code;
            this.product = product;
            this.count = count;
        }
    }

    record Result(String message, Product product, List<Coin> change) {
        static Result say(String message) { return new Result(message, null, List.of()); }
    }

    /** Coins the machine holds, used to pay out change. */
    static final class CoinBox {
        private final Map<Coin, Integer> coins = new EnumMap<>(Coin.class);

        void add(Coin c, int n) { coins.merge(c, n, Integer::sum); }

        void addAll(List<Coin> list) { list.forEach(c -> add(c, 1)); }

        /** Greedy change from the largest coin down; returns null when exact change is impossible. */
        List<Coin> planChange(int amount) {
            List<Coin> out = new ArrayList<>();
            Coin[] desc = Coin.values();
            for (int i = desc.length - 1; i >= 0 && amount > 0; i--) {
                int use = Math.min(amount / desc[i].cents, coins.getOrDefault(desc[i], 0));
                for (int k = 0; k < use; k++) out.add(desc[i]);
                amount -= use * desc[i].cents;
            }
            return amount == 0 ? out : null;
        }

        void remove(List<Coin> list) { list.forEach(c -> coins.merge(c, -1, Integer::sum)); }
    }

    // ---------- the State pattern ----------
    interface State {
        Result insert(VendingMachine m, Coin c);

        Result select(VendingMachine m, String code);

        Result cancel(VendingMachine m);
    }

    static final class Idle implements State {
        public Result insert(VendingMachine m, Coin c) {
            m.credit.add(c);
            m.state = new HasMoney();
            return Result.say("Credit " + m.creditCents());
        }

        public Result select(VendingMachine m, String code) { return Result.say("Insert coins first"); }

        public Result cancel(VendingMachine m) { return Result.say("Nothing to return"); }
    }

    static final class HasMoney implements State {
        public Result insert(VendingMachine m, Coin c) {
            m.credit.add(c);
            return Result.say("Credit " + m.creditCents());
        }

        public Result select(VendingMachine m, String code) {
            Slot slot = m.slots.get(code);
            if (slot == null) return Result.say("No such item " + code);
            if (slot.count == 0) return Result.say(slot.product.name() + " is sold out");
            int credit = m.creditCents(), price = slot.product.priceCents();
            if (credit < price) return Result.say("Insert " + (price - credit) + " more");
            // Plan the change against the coins already in the box plus the ones just inserted.
            m.box.addAll(m.credit);
            List<Coin> change = m.box.planChange(credit - price);
            if (change == null) {
                m.box.remove(m.credit);
                return Result.say("Exact change only, choose another item or cancel");
            }
            m.box.remove(change);
            slot.count--;
            m.credit.clear();
            m.state = new Idle();
            m.listener.onSale(slot.code, slot.count);
            return new Result("Enjoy your " + slot.product.name(), slot.product, change);
        }

        public Result cancel(VendingMachine m) {
            List<Coin> back = List.copyOf(m.credit);
            m.credit.clear();
            m.state = new Idle();
            return new Result("Returned", null, back);
        }
    }

    /** Door open for restocking: every customer button is refused. */
    static final class Maintenance implements State {
        public Result insert(VendingMachine m, Coin c) {
            return new Result("Out of service", null, List.of(c)); // coin drops straight back out
        }

        public Result select(VendingMachine m, String code) { return Result.say("Out of service"); }

        public Result cancel(VendingMachine m) { return Result.say("Out of service"); }
    }

    /** Observer: the operator's dashboard hears about every sale and low stock. */
    interface SaleListener { void onSale(String code, int left); }

    // ---------- the machine ----------
    private final Map<String, Slot> slots = new LinkedHashMap<>();
    private final CoinBox box = new CoinBox();
    private final List<Coin> credit = new ArrayList<>();
    private final SaleListener listener;
    private State state = new Idle();

    VendingMachine(SaleListener listener) { this.listener = listener; }

    int creditCents() { return credit.stream().mapToInt(c -> c.cents).sum(); }

    // One physical keypad, but a remote API could call too: every entry point is synchronized.
    synchronized Result insert(Coin c) { return state.insert(this, c); }

    synchronized Result select(String code) { return state.select(this, code); }

    synchronized Result cancel() { return state.cancel(this); }

    synchronized Result openForService() {
        Result r = state instanceof HasMoney ? cancel() : Result.say("Service mode");
        state = new Maintenance();
        return r;
    }

    synchronized void restock(String code, Product p, int count) {
        if (!(state instanceof Maintenance)) throw new IllegalStateException("Open the machine first");
        slots.computeIfAbsent(code, k -> new Slot(k, p, 0)).count += count;
    }

    synchronized void loadCoins(Coin c, int n) { box.add(c, n); }

    synchronized void closeService() { state = new Idle(); }

    String stateName() { return state.getClass().getSimpleName(); }

    // ---------- demo ----------
    static void show(VendingMachine m, String action, Result r) {
        String out = "%-16s -> %-48s state=%s".formatted(action, r.message(), m.stateName());
        if (!r.change().isEmpty()) out += " coins=" + r.change();
        System.out.println(out);
    }

    public static void main(String[] args) {
        VendingMachine m = new VendingMachine((code, left) -> {
            if (left <= 1) System.out.println("  [dashboard] slot " + code + " low: " + left + " left");
        });
        show(m, "service", m.openForService());
        m.restock("A1", new Product("Water", 60), 5);
        m.restock("B2", new Product("Chips", 85), 2);
        m.loadCoins(Coin.FIVE, 4);
        m.loadCoins(Coin.TEN, 4);
        m.loadCoins(Coin.TWENTY, 2);
        m.closeService();

        show(m, "select A1", m.select("A1"));
        show(m, "insert 50", m.insert(Coin.FIFTY));
        show(m, "select A1", m.select("A1"));
        show(m, "insert 50", m.insert(Coin.FIFTY));
        Result water = m.select("A1");
        show(m, "select A1", water);
        if (water.product() == null) throw new AssertionError("sale failed");

        show(m, "insert 100", m.insert(Coin.HUNDRED));
        show(m, "select B2", m.select("B2"));
        show(m, "insert 100", m.insert(Coin.HUNDRED));
        show(m, "select B2", m.select("B2"));
        show(m, "insert 100", m.insert(Coin.HUNDRED));
        show(m, "select B2", m.select("B2"));
        show(m, "cancel", m.cancel());
        show(m, "service", m.openForService());
        show(m, "insert 10", m.insert(Coin.TEN));
    }
}

Notes

Requirements

Pin down the behaviour. A customer inserts coins of fixed values, picks a product by slot code, gets the product and any change, or presses cancel to get every coin back. Sold-out and unknown slots give a clear message. An operator opens the machine to restock products and load coins for change, and wants an alert when a slot is nearly empty. Card payments and networking are out of scope for now.

Clarify the tricky parts. Is change paid from a limited coin box? Yes, so the machine can run out of the right coins. If it cannot make exact change, it refuses the sale, keeps the credit and says so, rather than cheating the customer. A coin inserted during restocking drops straight back out. These answers become the behaviour of specific states, so ask them before drawing anything.

Requirements
  • insert coins: 5, 10, 20, 50, 100
  • select a product by slot code
  • dispense and return change
  • cancel returns all coins
  • sold out and wrong code handled
  • operator restocks products
  • and loads change coins
  • alert when a slot runs low
  • out of scope: cards, network
Clarify first
  • change from a limited box?
  • yes: coins can run out
  • cannot make change?
  • refuse, keep credit, say so
  • insert during restocking?
  • coin drops straight back
  • select before paying?
  • show the price, no sale
  • one customer at a time?
  • yes, but calls may race

Entities

The entities. The machine has slots, keyed by a code like A1. Each slot holds one product and a count. A product is an immutable record of name and price in cents. Coins are an enum with a value each, and the coin box counts how many of each coin the machine holds for change. The customer's inserted coins are a separate list, the credit, because they must be returned exactly as given on cancel.

Why not if statements

Why not just use flags and if statements? Because every method ends up checking every flag: is the door open, is there credit, is it enough, is it sold out. Insert and cancel repeat the same chain. When the business adds a new mode, say a dispensing error, you edit all three methods and hope you did not miss a branch. The behaviour is spread by method, when it should be grouped by situation.

The naive version
void select(String code) {
  if (inService) { ... }
  else if (credit == 0) { ... }
  else if (credit < price) { ... }
  else if (soldOut) { ... }
  else { ... }
}
// insert() and cancel() repeat the
// same flags; a new mode edits all 3

State pattern

The State pattern flips it around. Define one interface with every action: insert, select and cancel. Write one class per situation: Idle, HasMoney and Maintenance. The machine holds a reference to the current state and simply delegates each button to it. Each state class answers every action for its own situation, and a state changes the machine's current state when a transition happens.

Before writing classes, write the transition table, because interviewers often ask for it. Idle plus a coin moves to HasMoney. HasMoney plus more coins stays. A successful select dispenses, pays change and returns to Idle. A short select stays put and says how much more is needed. Cancel returns the credit and goes to Idle. Opening for service moves to Maintenance, where coins drop straight back out.

State interface
interface State {
  Result insert(VendingMachine m, Coin c);
  Result select(VendingMachine m, String s);
  Result cancel(VendingMachine m);
}

Result select(String code) {
  return state.select(this, code);
}
Transition table
  • Idle + insert -> HasMoney
  • Idle + select -> "insert coins"
  • HasMoney + insert -> HasMoney
  • HasMoney + select ok -> Idle
  • (dispense + change)
  • HasMoney + select short -> stay
  • HasMoney + cancel -> Idle
  • (return credit)
  • any + service -> Maintenance
  • Maintenance + insert -> refund

Flow: buying

Here is the buying flow inside HasMoney. Look up the slot; an unknown code or a sold-out slot returns a message and stays in the same state. If the credit is short, say how much more is needed. Otherwise add the inserted coins to the box and plan the change. If change is impossible, undo and ask for exact change. Only when everything checks out do we commit: remove the change coins, decrement the slot, clear the credit and go back to Idle.

HasMoney.select(code)
slot = slots.get(code)
unknown or count 0 -> message, stay
credit < price -> "insert 10 more"
box.addAll(credit)
change = box.planChange(credit - price)
null -> undo, "exact change only"
box.remove(change); slot.count--
credit.clear(); state = new Idle()
listener.onSale(code, slot.count)

Making change

Making change is greedy: take as many of the largest coin as possible, then the next, and so on. For standard coin sets with plenty of coins, greedy gives the fewest coins. With a limited box it can fail even when an answer exists, for example when using one big coin blocks the rest. Then a small dynamic programming search over the coin counts finds an answer if one exists. Mention that trade-off; it is a favourite follow-up.

planChange(amount)
for coin from largest to smallest:
  use = min(amount / coin, have[coin])
  take use coins; amount -= use * coin
return amount == 0 ? coins : null

owe 40, box has two 20s: [20, 20]
owe 60, box: one 50, three 20s
  greedy: 50, then 10 left: stuck
  but 20 + 20 + 20 works: use DP

Maintenance

The operator side. Opening for service first refunds any customer credit, then switches to Maintenance. Restocking checks that the machine is in Maintenance, so nobody can change stock in the middle of a sale. The operator loads coins for change, then closes the door and the machine returns to Idle. Customer buttons in Maintenance are all polite refusals, and an inserted coin drops straight back.

Operator actions
openForService():
  if HasMoney, refund the credit first
  state = new Maintenance()
restock(code, product, count):
  only allowed in Maintenance
loadCoins(coin, n)
closeService(): state = new Idle()

Observer: low stock

Low-stock alerts use the Observer pattern. After every sale the machine calls a sale listener with the slot and the count left. The operator's dashboard raises an alert when one or zero are left, a sales report counts products, and a refill route planner could subscribe later. The machine knows nothing about any of them, so adding a new consumer never touches the selling code.

SaleListener
interface SaleListener {
  void onSale(String code, int left);
}

dashboard: alert when left <= 1
sales report: count per product
a refill route planner later

Concurrency

Concurrency. A physical machine has one keypad, but a remote API or a second panel could call at the same time as a customer. The state, credit, coin box and stock change together in one step, so the simplest correct answer is one lock: every public method is synchronized on the machine. Each call takes microseconds and calls are rare, so a single lock costs nothing. Say why fine-grained locking is not worth it here.

Thread safety
  • one keypad, but a remote API or
  • a second panel can race
  • insert, select, cancel, service:
  • all synchronized on the machine
  • state + credit + box + stock
  • change together: one lock is
  • simplest and correct
  • operations are microseconds:
  • no contention worth fixing

Extensibility

Extending it. Card or UPI payment becomes a payment strategy used by HasMoney. A motor that can jam adds a Dispensing state that refunds if the product never drops. Combo discounts are a pricing rule. A second currency turns the coin enum into a denomination class. Remote telemetry is just one more listener. Notice that none of these require editing the existing states.

Extension points
  • card or UPI payment:
  • a PaymentStrategy in HasMoney
  • motor jam: a Dispensing state
  • that refunds on failure
  • combo offers: a Pricing rule
  • multiple currencies: Coin
  • becomes a Denomination class
  • remote telemetry: one more
  • SaleListener

Testing

The full code is below the player. The demo restocks in Maintenance, then walks every transition: select with no money, a short credit, a sale with change in two twenty coins, selling a slot down to zero with low-stock alerts, a sold-out select followed by cancel, and a coin inserted during service that comes straight back. One pass through the transition table is a good unit test plan to describe too.

Run it
select A1   -> Insert coins first
insert 50   -> Credit 50
select A1   -> Insert 10 more
insert 50   -> Credit 100
select A1   -> Enjoy your Water
              coins=[TWENTY, TWENTY]
select B2   -> Chips is sold out
cancel      -> Returned [HUNDRED]
insert 10   -> Out of service [TEN]

Follow-ups

Expect these follow-ups. Why the State pattern instead of a switch on an enum? A switch is fine for three states, but it puts every situation in every method, and the pattern scales as modes grow. When greedy change fails, use a small dynamic programming search. After a power cut mid-sale, persist the credit and refund on boot. And since our states hold no data, each could be a shared singleton instead of a new object.

Follow-ups to expect
  • why State over a switch?
  • where is the transition logic?
  • inside each state class
  • greedy change fails: then?
  • DP over coin counts
  • power cut mid-sale?
  • persist credit, refund on boot
  • states as singletons?
  • yes, if they hold no data

Say it like this

Here is the short version. The machine delegates every button to its current state: Idle, HasMoney or Maintenance. A sale checks the slot and the credit, plans change from a limited coin box, and only then commits, all under one lock. Low-stock alerts are an observer. A new mode is a new state class, and the transition table is the spec.

In the interview
  • "The machine delegates every
  • button to its current State:
  • Idle, HasMoney, Maintenance.
  • A sale checks slot and credit,
  • plans change from the coin box,
  • then commits in one step under
  • one lock. Low stock is an
  • observer. New modes are new
  • state classes."

Interview questions

Why is the State pattern a good fit for a vending machine?

The same buttons mean different things in different situations. One class per state keeps each situation’s rules together, the machine just delegates, and a new mode such as Dispensing or Maintenance is a new class rather than edits to every method.

What states would you define, and what moves between them?

Idle, HasMoney and Maintenance. Inserting a coin moves Idle to HasMoney; a successful sale or cancel moves back to Idle; opening for service moves any state to Maintenance after refunding credit; closing service returns to Idle.

How does the machine make change, and when does greedy fail?

Greedy takes the largest coins first. It is optimal for standard coin systems with unlimited coins, but with a limited coin box it can fail even when change is possible; a dynamic programming search over coin counts fixes that.

What happens if the machine cannot make exact change?

It refuses the sale before changing anything, keeps the customer’s credit, and asks for exact change or another item. Planning first and committing only on success means a failed sale leaves no partial updates.

How do you keep the machine safe if two calls arrive at once?

State, credit, stock and coins change together, so every public method is synchronized on the machine. Calls are rare and take microseconds, so a single lock is simple, correct and not a bottleneck.

How would you add card payments?

Introduce a PaymentStrategy used by HasMoney (or a new state for card flows) with coin and card implementations. The selection and dispensing logic stays the same; only how credit is obtained changes.

How do operators get low-stock alerts?

Observer: after each sale the machine notifies registered SaleListeners with the slot code and remaining count; a dashboard listener alerts when one or none is left. The machine is unaware of who listens.