A vending machine has one button labelled "A1". If you press it before inserting money, the screen asks for coins. If you press it after inserting enough money, you get a packet of chips. If the machine is empty, you get "Sold out". The button is the same every time. The answer depends on what has happened to the machine so far.
Many objects work like this. An ATM ignores "withdraw" until a PIN is accepted. An order can be cancelled before it ships and not after. A lift door opens when the lift is stopped at a floor, and never while the lift is moving. Each object has a few situations it can be in, and each situation has its own rules.
The State pattern gives each situation its own class. In this article we build a small vending machine twice. The first version uses a status field and a switch in every method. The second uses the State pattern. Then we look at what the pattern costs, when a plain switch is the better choice, and how this shows up in interviews.
All the code is Java, and all of it compiles and runs. Every snippet is cut from the finished project, and the Open file button on a snippet shows the whole file in a code browser.
The machine we are building
The machine sells a few products, each in a slot with a code like A1. It takes 5¢, 10¢, 25¢ and $1 coins. Four things can happen to it:
- A customer inserts a coin.
- A customer selects a product by its code.
- A customer cancels, and wants their money back.
- An operator restocks a slot.
At any moment the machine is in one of three situations:
- Idle. No money inserted. The machine is waiting for a customer.
- Has money. A customer has inserted coins and has not bought anything yet.
- Sold out. Every slot is empty.
This drawing is a state diagram. It is the most useful thing to draw before writing any code. Each box is a state, each arrow is an action that changes the state, and the label on the arrow is the action. When we write the code, every arrow that leads to a different state becomes a line that changes the state.
The first version: a status field and a switch
The obvious way to write this is an enum for the three states, a field that holds the current one, and a switch on that field inside every method:
public class VendingMachine { enum Status { IDLE, HAS_MONEY, SOLD_OUT } private final Inventory inventory = new Inventory(); private final Hardware hardware; private Status status = Status.SOLD_OUT; private int balance; public VendingMachine(Hardware hardware) { this.hardware = hardware; } public void insertCoin(Coin coin) { switch (status) { case IDLE -> { balance += coin.value(); hardware.show("Balance: " + Money.format(balance)); status = Status.HAS_MONEY; } case HAS_MONEY -> { balance += coin.value(); hardware.show("Balance: " + Money.format(balance)); } case SOLD_OUT -> { hardware.show("Sold out"); hardware.returnCoins(coin.value()); } } }selectProduct, cancel and restock look the same: a switch with one branch per state. Here is the start of selectProduct:
public void selectProduct(String code) { switch (status) { case IDLE -> hardware.show("Insert coins first"); case HAS_MONEY -> { Optional<Product> found = inventory.find(code); if (found.isEmpty()) { hardware.show("No product at " + code); return; } Product product = found.get(); if (!inventory.inStock(code)) { hardware.show(product.name() + " is sold out. Pick another or cancel"); return; }This code works. For three states and four actions it is easy to read, and if the machine never changes, it is a fine answer. The trouble starts when it grows.
The rules for one state are spread across every method. To learn what the machine does when it has money, you have to read the HAS_MONEY branch of insertCoin, then of selectProduct, then of cancel, then of restock. Nothing in the code puts them together.
A new state touches every method. Suppose the machine gets a MAINTENANCE state, for when an operator has the door open. We add one more branch to all four switch statements. If we forget one, Java does not complain. A switch statement over an enum does not have to cover every value, so a forgotten cancel branch compiles, and in maintenance mode cancel silently does nothing.
The class grows with states times actions. Three states and four actions make twelve branches in one class. Six states and eight actions make forty-eight.
This figure is the whole pattern. Both versions contain the same twelve pieces of behaviour. The switch version groups them by action, so each method knows about every state. The State pattern groups them by state, so each class knows about every action. The better grouping depends on which way the grid is going to grow, and we come back to that in What it costs.
The idea
The pattern works like this:
- Each state becomes a class. All the state classes implement one interface, with one method per action.
- The machine keeps a reference to one state object, the current one.
- When an action arrives, the machine hands it to the current state object and does nothing else itself.
- To change state, the machine swaps that reference for a different state object.
From outside, the machine seems to turn into a different machine after the first coin goes in. It is the same object. Only the state object it points to has changed.
The pattern has three names for its parts. The object with the changing behaviour, our VendingMachine, is the context. The interface is the state. The classes that implement it, IdleState, HasMoneyState and SoldOutState, are the concrete states.
Building it, step by step
Step 1: one interface, one method per action
Each of the four actions becomes a method on the State interface:
interface State { void insertCoin(VendingMachine machine, Coin coin); void selectProduct(VendingMachine machine, String code); void cancel(VendingMachine machine); void restock(VendingMachine machine, Product product, int count);}Every state class must implement all four methods. This is a good thing. A state cannot forget an action, because the class does not compile until every method exists. The compiler now checks what the switch version left to our memory.
The interface has no public modifier, so only classes in the vending package can see it. Customers and operators talk to the machine, never to a state.
Each method takes the machine as its first parameter. That is our first decision.
How does a state reach the machine it belongs to?
Each state keeps a reference to the machine
The state takes the machine in its constructor and keeps it in a field. This is the version in many textbooks. It means every machine needs its own state objects, and the machine and its states have to be wired to each other when the machine is built.
The machine passes itself in on every callOur pick
state.insertCoin(this, coin). The states hold no fields at all, so a state object belongs to no particular machine. We create a new one on each transition because new IdleState() reads clearly. Since they hold nothing, one shared static final instance of each state would work just as well, and would save the small allocation. There is no wiring to get wrong either way.
Step 2: the machine hands every action to its state
With the interface in place, the machine's public methods become one line each:
public class VendingMachine { private final Inventory inventory = new Inventory(); private final Hardware hardware; private State state = new SoldOutState(); private int balance; public VendingMachine(Hardware hardware) { this.hardware = hardware; } public void insertCoin(Coin coin) { state.insertCoin(this, coin); } public void selectProduct(String code) { state.selectProduct(this, code); } public void cancel() { state.cancel(this); } public void restock(Product product, int count) { state.restock(this, product, count); }The machine no longer contains a single rule. It does not know that you need money before you can buy, or that an empty machine returns coins. It holds the data (inventory, hardware, balance) and the current state, and it forwards every action.
The machine creates its own Inventory, so no outside code can change the stock behind the states' backs. A new machine is empty, so it starts in SoldOutState. The operator's first restock moves it to IdleState.
Hardware is an interface for the physical parts: the screen, the chute that drops the product, and the coin return. The states call it to show messages and hand things out. In the demo it prints to the console, and in a test it can be a fake that records what happened.
Step 3: each state answers every action
Here is the whole of IdleState, the machine waiting for a customer:
class IdleState implements State { @Override public void insertCoin(VendingMachine machine, Coin coin) { machine.addToBalance(coin.value()); machine.hardware().show("Balance: " + Money.format(machine.balance())); machine.changeState(new HasMoneyState()); } @Override public void selectProduct(VendingMachine machine, String code) { machine.inventory().find(code).ifPresentOrElse( product -> machine.hardware().show(product.name() + " costs " + Money.format(product.price()) + ". Insert coins first"), () -> machine.hardware().show("No product at " + code)); } @Override public void cancel(VendingMachine machine) { machine.hardware().show("Nothing to cancel"); } @Override public void restock(VendingMachine machine, Product product, int count) { machine.inventory().add(product, count); machine.hardware().show("Restocked " + product.name()); }}Reading it top to bottom tells you everything an idle machine does. A coin goes into the balance and moves the machine to HasMoneyState. Selecting a product shows its price. Cancel has nothing to cancel. Restocking adds stock and stays idle.
The highlighted line is a transition: an arrow from the state diagram, written as code. IdleState decides that after a coin, the next state is HasMoneyState.
HasMoneyState is where the real work happens. This is its selectProduct:
@Override public void selectProduct(VendingMachine machine, String code) { Inventory inventory = machine.inventory(); Hardware hardware = machine.hardware(); Optional<Product> found = inventory.find(code); if (found.isEmpty()) { hardware.show("No product at " + code); return; } Product product = found.get(); if (!inventory.inStock(code)) { hardware.show(product.name() + " is sold out. Pick another or cancel"); return; } int balance = machine.balance(); if (balance < product.price()) { hardware.show("Insert " + Money.format(product.price() - balance) + " more"); return; } inventory.removeOne(code); hardware.dispense(product); int change = balance - product.price(); if (change > 0) { hardware.returnCoins(change); } machine.clearBalance(); machine.changeState(inventory.isEmpty() ? new SoldOutState() : new IdleState()); }Three checks come first: the product exists, it is in stock, and the balance covers the price. If any check fails, the machine shows why and stays in HasMoneyState, so the customer can add coins, pick something else, or cancel. If all three pass, the machine takes the item from the inventory, drops it in the chute, returns the change and clears the balance.
The last line chooses the next state. If that was the last item in the machine, it goes to SoldOutState. Otherwise it goes back to IdleState.
Who decides the next state?
The machine, after each call
The state does its work and returns, and the machine looks up the next state in a table of (state, action) pairs. All the transitions sit in one place, which is easy to read. But the next state here depends on what happened inside the call: did the sale go through, and was it the last item? The table would need that information passed back out, and the rules would end up split between the state and the table.
Each state, at the end of its own methodOur pick
The state already knows what just happened, so it picks the next state itself. The cost is that states know about each other: HasMoneyState creates IdleState and SoldOutState. They are one small family in one package, so we accept this.
SoldOutState is short, because an empty machine refuses almost everything:
class SoldOutState implements State { @Override public void insertCoin(VendingMachine machine, Coin coin) { machine.hardware().show("Sold out"); machine.hardware().returnCoins(coin.value()); } @Override public void selectProduct(VendingMachine machine, String code) { machine.hardware().show("Sold out"); } @Override public void cancel(VendingMachine machine) { machine.hardware().show("Nothing to cancel"); } @Override public void restock(VendingMachine machine, Product product, int count) { machine.inventory().add(product, count); machine.hardware().show("Restocked " + product.name()); machine.changeState(new IdleState()); }}Notice line 7. An empty machine that receives a coin must give the coin back. If this method were left empty, the machine would quietly keep the customer's money. Every state has to answer every action, and "no" is still an answer that has to be written.
Step 4: only the states may change the machine
The states need to change the balance and swap the current state. But a customer should not be able to call changeState and jump straight to a free packet of chips. These methods are package-private: they have no access modifier, so only classes in the vending package can call them.
// Package-private: only the states may change the machine. void changeState(State next) { state = next; } Inventory inventory() { return inventory; } Hardware hardware() { return hardware; } int balance() { return balance; } void addToBalance(int amount) { balance += amount; } void clearBalance() { balance = 0; }Where does the balance live?
Inside HasMoneyState
new HasMoneyState(10) when the first coin arrives. Only one state has money, so only that state holds it, and an idle machine with a leftover balance becomes impossible. The machine can no longer show the balance on its own, though, and every coin has to create or update a state object.
In the machine, next to the inventoryOur pick
The balance is part of the machine, the same as its stock. States read and change it through balance(), addToBalance() and clearBalance(). Every state stays free of fields. We must remember to clear the balance on every path out of HasMoneyState. There are only two such paths, a sale and a cancel, and both do it.
Step 5: decide what "no" looks like
In this machine, wrong actions get a message on the screen: "Insert coins first", "Sold out", "Nothing to cancel". That fits a machine with a customer standing in front of it. A customer pressing the wrong button is normal, not an error.
Code that other code calls is different. If an Order in ShippedState receives cancel(), the caller has made a mistake, and the state should throw an IllegalStateException so the bug is found. The pattern does not decide this for you. Pick one style for the whole object, and make every state follow it. Our machine uses messages for the customer and exceptions for code errors. A restock with a count of zero comes from the operator's software, not from a person at the panel, so Inventory.add throws IllegalArgumentException for it.
The finished design
Here is one purchase, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package vending; public class VendingMachine { private final Inventory inventory = new Inventory(); private final Hardware hardware; private State state = new SoldOutState(); private int balance; public VendingMachine(Hardware hardware) { this.hardware = hardware; } public void insertCoin(Coin coin) { state.insertCoin(this, coin); } public void selectProduct(String code) { state.selectProduct(this, code); } public void cancel() { state.cancel(this); } public void restock(Product product, int count) { state.restock(this, product, count); } public String stateName() { return state.getClass().getSimpleName(); } // Package-private: only the states may change the machine. void changeState(State next) { state = next; } Inventory inventory() { return inventory; } Hardware hardware() { return hardware; } int balance() { return balance; } void addToBalance(int amount) { balance += amount; } void clearBalance() { balance = 0; }}The demo in demo/Main.java sends the machine through every state. Each line in brackets is the state the machine was in when the action arrived:
[SoldOutState] restock A1 and A2
screen: Restocked Chips
screen: Restocked Water
[IdleState] select A1
screen: Chips costs $2.00. Insert coins first
[IdleState] insert $1
screen: Balance: $1.00
[HasMoneyState] select A1
screen: Insert $1.00 more
[HasMoneyState] insert $1 and 25¢
screen: Balance: $2.00
screen: Balance: $2.25
[HasMoneyState] select A1
chute: Chips
coins: $0.25 returned
[IdleState] insert $1 twice, select A2
screen: Balance: $1.00
screen: Balance: $2.00
chute: Water
coins: $0.25 returned
[SoldOutState] insert 25¢
screen: Sold out
coins: $0.25 returned
[SoldOutState] restock A1
screen: Restocked Chips
[IdleState] doneFollow the brackets. The machine starts empty, in SoldOutState, and the first restock moves it to IdleState. The first select A1 arrives in IdleState and only shows the price. After $1 the machine is in HasMoneyState, and selecting chips asks for $1.00 more. After $2.25 the sale goes through with $0.25 change. Buying the water empties the machine, so the next coin arrives in SoldOutState and comes straight back. Restocking chips returns the machine to IdleState.
What it costs
The pattern makes one kind of change cheap and another kind expensive.
Adding a state is cheap. A MaintenanceState is one new class. The compiler makes us write all four methods in it. The existing states change only where an arrow leads into the new state. There is a catch: a new state often brings new actions with it. Maintenance needs openDoor() and closeDoor(), and those are new actions, with the cost below.
Adding an action is expensive. A new refillCoins() action, for an operator topping up the change tube, means one new method on State, and then a new method in every state class. In the switch version this is one new method in one class.
So the question to ask is: which way will this object grow? Machines, workflows and protocols gain states over time: a maintenance mode, an on-hold status, a retry state. Their list of actions changes less often. That is where the State pattern pays off.
There are smaller costs too. Twelve branches in one file become a dozen methods across four files. To follow one purchase you jump between classes, which is why the code browser on this page exists. And the states are coupled to each other, because each one creates the next.
When a switch or a table is better
If the states differ only in which transitions are allowed, and not in what they do, the State pattern is too much. An order status is the usual example: placed, paid, shipped, delivered, cancelled. What changes between states is mostly "is this move allowed?". A map from each status to its allowed next statuses says that in a few lines:
enum OrderStatus { PLACED, PAID, SHIPPED, DELIVERED, CANCELLED } private static final Map<OrderStatus, Set<OrderStatus>> ALLOWED = Map.of( OrderStatus.PLACED, Set.of(OrderStatus.PAID, OrderStatus.CANCELLED), OrderStatus.PAID, Set.of(OrderStatus.SHIPPED, OrderStatus.CANCELLED), OrderStatus.SHIPPED, Set.of(OrderStatus.DELIVERED), OrderStatus.DELIVERED, Set.of(), OrderStatus.CANCELLED, Set.of()); void moveTo(OrderStatus next) { if (!ALLOWED.get(status).contains(next)) { throw new IllegalStateException(status + " cannot move to " + next); } status = next;}The vending machine is different. In HasMoneyState, selecting a product runs three checks and a sale. In IdleState, the same action shows a price. The behaviour itself changes, not only the permission, and that is when separate classes help.
Two more cases where we would not use the pattern:
- Two states and one or two actions. A
boolean isOpenand anifare clearer than an interface and two classes. - States that will not grow. If the three states above were fixed forever, the
switchversion would be fine. A pattern is a bet on how the code will change.
Java also has a middle option: an enum whose constants each override a method. All the states live in one file and the compiler still checks that every state implements every action:
enum Light { RED { @Override Light next() { return GREEN; } }, GREEN { @Override Light next() { return YELLOW; } }, YELLOW { @Override Light next() { return RED; } }; abstract Light next();}This works well when states are small and hold no data. Once a state's methods grow past a few lines, separate classes are easier to read.
State or Strategy?
This is a common interview question, because the two class diagrams are the same: a class holds a reference to an interface, and several classes implement it. The difference is in who chooses the implementation, and when.
| State | Strategy | |
|---|---|---|
| Who picks the object | The states themselves, as things happen | The code that creates the context, usually once |
| Does it change by itself | Yes: after a coin, the machine is in a new state | No: it changes only when someone outside swaps it |
| Do the implementations know each other | Often: each state usually creates the next one | No, each one stands alone |
| Example | Vending machine: Idle, HasMoney, SoldOut | Parking fee: hourly, flat rate, weekend rate |
A short way to say it: with Strategy, the client chooses how the work is done. With State, the object's own history chooses.
In an interview
The State pattern sits inside many classic low-level design questions: vending machine, ATM, lift, traffic signal, order lifecycle, document approval and seat booking (held, confirmed, expired). It rarely appears as "implement the State pattern". It appears as an object whose rules change over its life.
A good order for presenting it:
- Draw the state diagram first. List the states, then the actions, then the arrows. It takes two minutes, and the interviewer can check your understanding before you write any code.
- Fill in the states × actions table out loud. "In Sold out, insert coin returns the coin." This is where missing cases show up.
- Then write the interface and one or two states in full. You rarely need every state written out. The interviewer wants to see the shape and one non-trivial transition.
Common mistakes:
- Empty methods for actions a state does not allow. An empty
insertCoininSoldOutStatekeeps the coin. Every "no" needs to be written. - State classes that keep their own copy of the machine's data, such as a balance in the state and another in the machine. The two drift apart. Keep each piece of data in one place.
- A state for every small detail. Here
dispense()finishes beforeselectProductreturns, so aDispensingStatewould last for one method call, add a class and change nothing. A state is worth having only if the machine can be in it when the next action arrives. On real hardware, where dispensing takes a few seconds and a customer can press buttons meanwhile,DispensingStateearns its place. - Assuming the machine always has change. Ours does, to keep the example small. A real machine can run out of coins for change, and "exact change only" is a common follow-up. It is a check inside
HasMoneyState.selectProduct, not a new state, because the machine can still sell to a customer with the exact amount. - Forgetting threads. This machine assumes one customer at a time, which is true for a physical machine. If many threads can call the context at once, as with an order updated by several services, make the context's public methods
synchronizedso each action runs fully before the next starts.
Summary
- Use the State pattern when an object answers the same action differently depending on its situation, and the number of situations is likely to grow.
- Draw the state diagram first. Each arrow to a different state becomes one line of code that changes the state.
- The context holds the data and one state object, and forwards every action. Each state class answers every action, including the ones it refuses.
- Adding a state is cheap. Adding an action touches every state.
- If the states differ only in which moves are allowed, an enum with a transition table is simpler.