State Pattern
An empty vending machine ignores coins, one holding your money will sell you something, and one in maintenance mode answers only to a technician's key. Write that as one class with a status field and every method grows a switch on the status, so the rules for any single mode end up scattered across the class.
The State pattern turns each mode into its own object. The machine holds its current state object and forwards every request to it; changing mode means swapping the object. This page goes deeper than the behavioral patterns overview: a complete thread-safe vending machine in three languages, an order lifecycle as a transition table, and the question interviewers actually ask, which is when a plain enum and a switch is the better answer.
Intent
Let an object change its behaviour when its internal mode changes, by delegating each request to an object that represents the current mode. From the outside, it looks as if the object changed its class.
- Behaviour is grouped by state, not by operation. Everything the machine does while holding money lives in one class.
- The context delegates. Its public methods become one-liners that call the current state.
- Transitions are explicit. A state decides the next state and tells the context, instead of a status field being reassigned deep inside a long method.
State is the object-oriented form of a finite state machine: a fixed set of states, a set of events, and a rule for each (state, event) pair. Keep that picture in mind, because sometimes the best implementation of a state machine is not the State pattern at all.
The problem
Here is the kind of code the pattern replaces. A vending machine has three modes: IDLE (stocked, no money inserted), HAS_MONEY and SOLD_OUT. Every public method switches on the mode.
import java.util.HashMap;
import java.util.Map;
enum Mode { IDLE, HAS_MONEY, SOLD_OUT }
class VendingMachine {
private Mode mode = Mode.SOLD_OUT;
private int balance;
private final Map<String, int[]> slots = new HashMap<>(); // code -> {price, count}
void insert(int cents) {
switch (mode) {
case IDLE -> { balance += cents; mode = Mode.HAS_MONEY; }
case HAS_MONEY -> balance += cents;
case SOLD_OUT -> throw new IllegalStateException("sold out");
}
}
int select(String code) { // returns change
switch (mode) {
case IDLE -> throw new IllegalStateException("insert money first");
case SOLD_OUT -> throw new IllegalStateException("sold out");
case HAS_MONEY -> {
int[] slot = slots.get(code);
if (slot == null || slot[1] == 0) throw new IllegalArgumentException("unavailable");
if (balance < slot[0]) throw new IllegalStateException("not enough money");
slot[1]--;
int change = balance - slot[0];
balance = 0;
mode = slots.values().stream().allMatch(s -> s[1] == 0) ? Mode.SOLD_OUT : Mode.IDLE;
return change;
}
}
throw new AssertionError("unreachable");
}
int cancel() {
switch (mode) {
case HAS_MONEY -> { int refund = balance; balance = 0; mode = Mode.IDLE; return refund; }
default -> { return 0; }
}
}
void restock(String code, int price, int qty) {
slots.computeIfAbsent(code, c -> new int[]{price, 0})[1] += qty;
if (mode == Mode.SOLD_OUT) mode = Mode.IDLE;
}
}
With three modes and four operations, this is still readable, and it's about where it stops. Look at what happens when the product owner asks for one more mode: maintenance, entered with a technician key, during which the machine refuses coins and sales but allows restocking and a cash-box audit.
insert,select,cancelandrestockall need a newcase. So does every future method, such asauditorpressServiceKey.- To understand what the machine does in maintenance, you read four methods and assemble the answer in your head. The rules for one mode are smeared across the class.
- Transitions hide in the middle of methods (
mode = Mode.IDLEon line 5 of a branch). There is no single place that lists the legal transitions, so it is easy to add an illegal one by accident. - A
switchstatement over an enum is not checked for exhaustiveness, which is why the code needsthrow new AssertionError("unreachable"). In a Python version with string modes, a typo such as"HAS_MONY"silently falls through to theelsebranch.
This is a specific case of the leaky enum mistake: the same switch on the same field, repeated in several places. The cure is to keep the behaviour for each constant in one place.
Structure
classDiagram
class VendingMachine {
-state: MachineState
-balanceCents: int
-slots: Map
+insert(cents) void
+select(code) Vend
+cancel() int
+restock(code, product, price, qty) void
+setState(next) void
}
class MachineState {
<<interface>>
+name() String
+insert(m, cents) void
+select(m, code) Vend
+cancel(m) int
+restocked(m) void
}
class Idle {
+insert(m, cents) void
}
class HasMoney {
+insert(m, cents) void
+select(m, code) Vend
+cancel(m) int
}
class SoldOut {
+select(m, code) Vend
+restocked(m) void
}
VendingMachine --> MachineState : current
MachineState <|.. Idle
MachineState <|.. HasMoney
MachineState <|.. SoldOut
HasMoney ..> VendingMachine : calls setState
Each concrete state overrides only the operations that do something in that mode. Everything else falls back to a default on the interface that rejects the request, which is how an illegal operation produces a clear error instead of a silent no-op.
Participants
| Participant | In the example | Responsibility |
|---|---|---|
| Context | VendingMachine | The object clients use. Owns the data (balance, slots), holds the current state, forwards each request to it, and exposes a narrow set of helpers that states use to change data and switch state. |
| State interface | MachineState | Declares one method per event the context can receive. Each method takes the context as a parameter, so state objects can be shared. |
| Concrete states | Idle, HasMoney, SoldOut | Implement the behaviour for one mode, and decide the next state. |
| Client | the demo, a UI, a coin acceptor driver | Calls the context. Never sees state objects. |
Two design decisions hide in this table, and interviewers like to probe both.
Who triggers the transition? Here, states do: HasMoney.select picks Idle or SoldOut. That keeps each mode self-contained, at the cost of states knowing about each other. Fine with a handful of states; with dozens, move to a transition table or a statechart library.
Where does the data live? In the context. These states hold no fields, so one instance of each is shared by every machine, which is why the context is passed into every method. If a state needs its own data (such as when maintenance began), store it on the context or create a fresh state object per transition.
Implementation
The full machine follows. Each version starts empty (SoldOut), validates coins at the boundary, makes every public method atomic with a lock, and ends with a demo that asserts the transitions.
import java.util.LinkedHashMap;
import java.util.Map;
public class VendingDemo {
public static void main(String[] args) {
VendingMachine vm = new VendingMachine();
assert vm.stateName().equals("SoldOut");
vm.restock("A1", "Cola", 150, 1);
vm.restock("B2", "Chips", 100, 1);
assert vm.stateName().equals("Idle");
vm.insert(100);
vm.insert(100);
assert vm.stateName().equals("HasMoney");
Vend cola = vm.select("A1");
assert cola.product().equals("Cola") && cola.changeCents() == 50;
assert vm.stateName().equals("Idle");
vm.insert(50);
try { vm.select("B2"); assert false; }
catch (IllegalStateException e) { assert e.getMessage().contains("50 more"); }
assert vm.cancel() == 50 && vm.stateName().equals("Idle");
vm.insert(100);
Vend chips = vm.select("B2");
assert chips.changeCents() == 0 && vm.stateName().equals("SoldOut");
try { vm.insert(25); assert false; }
catch (IllegalStateException e) { assert e.getMessage().startsWith("SoldOut"); }
System.out.println("vending machine: all assertions passed");
}
}
record Vend(String product, int changeCents) {}
final class Slot {
final String product;
final int priceCents;
int count;
Slot(String product, int priceCents, int count) {
this.product = product; this.priceCents = priceCents; this.count = count;
}
}
interface MachineState {
String name();
default void insert(VendingMachine m, int cents) {
throw new IllegalStateException(name() + ": cannot accept money");
}
default Vend select(VendingMachine m, String code) {
throw new IllegalStateException(name() + ": insert money first");
}
default int cancel(VendingMachine m) { return 0; }
default void restocked(VendingMachine m) {}
}
final class Idle implements MachineState {
static final Idle INSTANCE = new Idle();
public String name() { return "Idle"; }
public void insert(VendingMachine m, int cents) {
m.addBalance(cents);
m.setState(HasMoney.INSTANCE);
}
}
final class HasMoney implements MachineState {
static final HasMoney INSTANCE = new HasMoney();
public String name() { return "HasMoney"; }
public void insert(VendingMachine m, int cents) { m.addBalance(cents); }
public Vend select(VendingMachine m, String code) {
Slot slot = m.slot(code);
if (slot == null || slot.count == 0) throw new IllegalArgumentException("unavailable: " + code);
if (m.balance() < slot.priceCents)
throw new IllegalStateException("need " + (slot.priceCents - m.balance()) + " more cents");
slot.count--;
int change = m.takeBalance() - slot.priceCents;
m.setState(m.isEmpty() ? SoldOut.INSTANCE : Idle.INSTANCE);
return new Vend(slot.product, change);
}
public int cancel(VendingMachine m) {
int refund = m.takeBalance();
m.setState(Idle.INSTANCE);
return refund;
}
}
final class SoldOut implements MachineState {
static final SoldOut INSTANCE = new SoldOut();
public String name() { return "SoldOut"; }
public Vend select(VendingMachine m, String code) {
throw new IllegalStateException("SoldOut: nothing to sell");
}
public void restocked(VendingMachine m) { m.setState(Idle.INSTANCE); }
}
final class VendingMachine {
private final Map<String, Slot> slots = new LinkedHashMap<>();
private int balanceCents;
private MachineState state = SoldOut.INSTANCE; // a new machine is empty
// Public API: validate, lock, delegate.
public synchronized void insert(int cents) {
if (cents <= 0) throw new IllegalArgumentException("coin must be positive");
state.insert(this, cents);
}
public synchronized Vend select(String code) { return state.select(this, code); }
public synchronized int cancel() { return state.cancel(this); }
public synchronized void restock(String code, String product, int priceCents, int qty) {
if (qty <= 0) throw new IllegalArgumentException("qty must be positive");
slots.computeIfAbsent(code, c -> new Slot(product, priceCents, 0)).count += qty;
state.restocked(this);
}
public synchronized String stateName() { return state.name(); }
// Narrow helpers for states (package-private).
void setState(MachineState next) { state = next; }
void addBalance(int cents) { balanceCents += cents; }
int balance() { return balanceCents; }
int takeBalance() { int b = balanceCents; balanceCents = 0; return b; }
Slot slot(String code) { return slots.get(code); }
boolean isEmpty() { return slots.values().stream().allMatch(s -> s.count == 0); }
}
from __future__ import annotations
import threading
from dataclasses import dataclass
class MachineError(Exception):
"""The current state does not allow this operation."""
@dataclass(frozen=True)
class Vend:
product: str
change_cents: int
@dataclass
class Slot:
product: str
price_cents: int
count: int
class MachineState:
name = "?"
def insert(self, m: VendingMachine, cents: int) -> None:
raise MachineError(f"{self.name}: cannot accept money")
def select(self, m: VendingMachine, code: str) -> Vend:
raise MachineError(f"{self.name}: insert money first")
def cancel(self, m: VendingMachine) -> int:
return 0
def restocked(self, m: VendingMachine) -> None:
pass
class Idle(MachineState):
name = "Idle"
def insert(self, m: VendingMachine, cents: int) -> None:
m.balance += cents
m.state = HAS_MONEY
class HasMoney(MachineState):
name = "HasMoney"
def insert(self, m: VendingMachine, cents: int) -> None:
m.balance += cents
def select(self, m: VendingMachine, code: str) -> Vend:
slot = m.slots.get(code)
if slot is None or slot.count == 0:
raise ValueError(f"unavailable: {code}")
if m.balance < slot.price_cents:
raise MachineError(f"need {slot.price_cents - m.balance} more cents")
slot.count -= 1
change, m.balance = m.balance - slot.price_cents, 0
m.state = SOLD_OUT if m.is_empty() else IDLE
return Vend(slot.product, change)
def cancel(self, m: VendingMachine) -> int:
refund, m.balance = m.balance, 0
m.state = IDLE
return refund
class SoldOut(MachineState):
name = "SoldOut"
def select(self, m: VendingMachine, code: str) -> Vend:
raise MachineError("SoldOut: nothing to sell")
def restocked(self, m: VendingMachine) -> None:
m.state = IDLE
# States hold no data, so one shared instance of each is enough.
IDLE, HAS_MONEY, SOLD_OUT = Idle(), HasMoney(), SoldOut()
class VendingMachine:
def __init__(self) -> None:
self.slots: dict[str, Slot] = {}
self.balance = 0
self.state: MachineState = SOLD_OUT # a new machine is empty
self._lock = threading.Lock()
def insert(self, cents: int) -> None:
if cents <= 0:
raise ValueError("coin must be positive")
with self._lock:
self.state.insert(self, cents)
def select(self, code: str) -> Vend:
with self._lock:
return self.state.select(self, code)
def cancel(self) -> int:
with self._lock:
return self.state.cancel(self)
def restock(self, code: str, product: str, price_cents: int, qty: int) -> None:
if qty <= 0:
raise ValueError("qty must be positive")
with self._lock:
self.slots.setdefault(code, Slot(product, price_cents, 0)).count += qty
self.state.restocked(self)
def is_empty(self) -> bool:
return all(s.count == 0 for s in self.slots.values())
@property
def state_name(self) -> str:
return self.state.name
if __name__ == "__main__":
vm = VendingMachine()
assert vm.state_name == "SoldOut"
vm.restock("A1", "Cola", 150, 1)
vm.restock("B2", "Chips", 100, 1)
assert vm.state_name == "Idle"
vm.insert(100)
vm.insert(100)
assert vm.state_name == "HasMoney"
assert vm.select("A1") == Vend("Cola", 50)
assert vm.state_name == "Idle"
vm.insert(50)
try:
vm.select("B2")
raise AssertionError("expected MachineError")
except MachineError as e:
assert "50 more" in str(e)
assert vm.cancel() == 50 and vm.state_name == "Idle"
vm.insert(100)
assert vm.select("B2") == Vend("Chips", 0)
assert vm.state_name == "SoldOut"
try:
vm.insert(25)
raise AssertionError("expected MachineError")
except MachineError as e:
assert str(e).startswith("SoldOut")
print("vending machine: all assertions passed")
class MachineError extends Error {}
type Vend = { product: string; changeCents: number };
type Slot = { product: string; priceCents: number; count: number };
interface MachineState {
readonly name: string;
insert(m: VendingMachine, cents: number): void;
select(m: VendingMachine, code: string): Vend;
cancel(m: VendingMachine): number;
restocked(m: VendingMachine): void;
}
// Default behaviour: reject anything the subclass does not override.
abstract class BaseState implements MachineState {
abstract readonly name: string;
insert(_m: VendingMachine, _cents: number): void {
throw new MachineError(`${this.name}: cannot accept money`);
}
select(_m: VendingMachine, _code: string): Vend {
throw new MachineError(`${this.name}: insert money first`);
}
cancel(_m: VendingMachine): number {
return 0;
}
restocked(_m: VendingMachine): void {}
}
class Idle extends BaseState {
readonly name = "Idle";
override insert(m: VendingMachine, cents: number): void {
m.balance += cents;
m.state = HAS_MONEY;
}
}
class HasMoney extends BaseState {
readonly name = "HasMoney";
override insert(m: VendingMachine, cents: number): void {
m.balance += cents;
}
override select(m: VendingMachine, code: string): Vend {
const slot = m.slots.get(code);
if (!slot || slot.count === 0) throw new RangeError(`unavailable: ${code}`);
if (m.balance < slot.priceCents) {
throw new MachineError(`need ${slot.priceCents - m.balance} more cents`);
}
slot.count--;
const change = m.balance - slot.priceCents;
m.balance = 0;
m.state = m.isEmpty() ? SOLD_OUT : IDLE;
return { product: slot.product, changeCents: change };
}
override cancel(m: VendingMachine): number {
const refund = m.balance;
m.balance = 0;
m.state = IDLE;
return refund;
}
}
class SoldOut extends BaseState {
readonly name = "SoldOut";
override select(_m: VendingMachine, _code: string): Vend {
throw new MachineError("SoldOut: nothing to sell");
}
override restocked(m: VendingMachine): void {
m.state = IDLE;
}
}
const IDLE = new Idle();
const HAS_MONEY = new HasMoney();
const SOLD_OUT = new SoldOut();
class VendingMachine {
// JavaScript runs one task at a time, so no lock is needed here.
readonly slots = new Map<string, Slot>();
balance = 0;
state: MachineState = SOLD_OUT;
insert(cents: number): void {
if (!Number.isInteger(cents) || cents <= 0) throw new RangeError("coin must be a positive integer");
this.state.insert(this, cents);
}
select(code: string): Vend {
return this.state.select(this, code);
}
cancel(): number {
return this.state.cancel(this);
}
restock(code: string, product: string, priceCents: number, qty: number): void {
if (qty <= 0) throw new RangeError("qty must be positive");
const slot = this.slots.get(code) ?? { product, priceCents, count: 0 };
slot.count += qty;
this.slots.set(code, slot);
this.state.restocked(this);
}
isEmpty(): boolean {
return [...this.slots.values()].every((s) => s.count === 0);
}
get stateName(): string {
return this.state.name;
}
}
// A plain boolean check (not `asserts cond`), so TypeScript doesn't narrow stateName between steps.
function assert(cond: boolean, msg = "assertion failed"): void {
if (!cond) throw new Error(msg);
}
function expectThrow(fn: () => unknown, text: string): void {
try { fn(); } catch (e) { assert(e instanceof MachineError && e.message.includes(text), String(e)); return; }
throw new Error(`expected MachineError containing "${text}"`);
}
const vm = new VendingMachine();
assert(vm.stateName === "SoldOut");
vm.restock("A1", "Cola", 150, 1);
vm.restock("B2", "Chips", 100, 1);
assert(vm.stateName === "Idle");
vm.insert(100);
vm.insert(100);
const cola = vm.select("A1");
assert(cola.product === "Cola" && cola.changeCents === 50 && vm.stateName === "Idle");
vm.insert(50);
expectThrow(() => vm.select("B2"), "50 more");
assert(vm.cancel() === 50 && vm.stateName === "Idle");
vm.insert(100);
assert(vm.select("B2").changeCents === 0 && vm.stateName === "SoldOut");
expectThrow(() => vm.insert(25), "SoldOut");
console.log("vending machine: all assertions passed");
Walking through the design
The context is thin on purpose. VendingMachine.select is lock, delegate. All the decisions live in HasMoney. An if (state == ...) inside the context means the pattern has started to leak.
Default rejection has a cost. Defaults keep each state short, and a new event touches only the interface plus the states that support it. But a forgotten override compiles silently. If that worries you more than boilerplate, drop the defaults so the compiler forces a decision for every (state, event) pair.
The states share instances. That's safe only because states hold no fields. It's the Flyweight idea, and why these "singletons" are harmless: global mutable state is what makes Singleton dangerous.
Narrow helpers in Java. States call package-private addBalance, takeBalance and setState. The Python and TypeScript versions let states touch balance and state directly, a common trade-off in languages with weak module privacy. Either way, outside callers use only insert, select, cancel and restock.
Concurrency lives in the context. Two threads selecting at once could both see one can of cola left and both dispense it. Locking each public method turns every event into one atomic step, and the states never lock because they always run inside that lock. It's the check-then-act rule from race conditions applied to a state machine.
Adding the maintenance mode
The change request that hurt the switch version becomes:
- A new
Maintenanceclass, which stays in maintenance on restock and handlesaudit. - One new event,
serviceKey(m), whose default moves toMaintenanceand whoseMaintenanceoverride returns toIdleorSoldOutdepending on stock. - One decision in
HasMoney.serviceKey: refund inserted money before entering maintenance? The question "what happens to the customer's money mid-sale?" now has an obvious home.
The vending machine as a state diagram
Before you write any state classes in an interview, draw the machine. It takes a minute and catches missing transitions early. The vending machine case study builds a larger version of this design end to end.
stateDiagram-v2
[*] --> SoldOut
SoldOut --> Idle : restock
Idle --> HasMoney : insert coin
HasMoney --> HasMoney : insert coin
HasMoney --> HasMoney : select, not enough money
HasMoney --> Idle : select, stock remains
HasMoney --> SoldOut : select, last item sold
HasMoney --> Idle : cancel, refund
Idle --> Maintenance : service key
SoldOut --> Maintenance : service key
Maintenance --> Idle : service key, stocked
Maintenance --> SoldOut : service key, empty
Read it as a checklist: every arrow is one setState call, every missing (state, event) pair is a clear rejection, and the self-loops are real transitions that stay put.
A second example: the order lifecycle
Vending machines are the classic interview prompt, but the most common state machine in production code is an order, a payment or a ticket moving through a lifecycle. Here is an e-commerce order:
stateDiagram-v2
[*] --> Created
Created --> Paid : pay
Created --> Cancelled : cancel
Paid --> Packed : pack
Paid --> Cancelled : cancel and refund
Packed --> Shipped : ship
Shipped --> Delivered : deliver
Delivered --> Returned : return within window
Cancelled --> [*]
Returned --> [*]
Delivered --> [*]
The interesting property of this machine is that most states have no behaviour of their own. A packed order doesn't compute anything differently from a paid order; it just allows a different set of next steps. When the states differ only in which transitions are legal, a full class per state is ceremony. A transition table does the job better: the machine becomes data, and one generic method enforces it.
type Status = "created" | "paid" | "packed" | "shipped" | "delivered" | "cancelled" | "returned";
type OrderEvent = "pay" | "pack" | "ship" | "deliver" | "cancel" | "return";
// Partial: a missing entry means "not allowed". Record<Status, ...> forces a row per status.
const NEXT: Record<Status, Partial<Record<OrderEvent, Status>>> = {
created: { pay: "paid", cancel: "cancelled" },
paid: { pack: "packed", cancel: "cancelled" },
packed: { ship: "shipped" },
shipped: { deliver: "delivered" },
delivered: { return: "returned" },
cancelled: {},
returned: {},
};
class Order {
status: Status = "created";
readonly history: Array<[Status, Status]> = [];
fire(event: OrderEvent): void {
const to = NEXT[this.status][event];
if (to === undefined) throw new Error(`${event} not allowed in ${this.status}`);
this.history.push([this.status, to]);
this.status = to;
}
}
function assert(cond: boolean, msg = "assertion failed"): asserts cond {
if (!cond) throw new Error(msg);
}
const order = new Order();
order.fire("pay");
order.fire("pack");
let rejected = false;
try { order.fire("cancel"); } catch (e) { rejected = e instanceof Error && e.message === "cancel not allowed in packed"; }
assert(rejected, "cancel after packing must be rejected");
order.fire("ship");
order.fire("deliver");
assert(order.status === "delivered" && order.history.length === 4);
console.log("order lifecycle: all assertions passed");
In Java the same table is an EnumMap<Status, EnumMap<Event, Status>>, and in Python a dict keyed by (status, event) tuples. The table has two big advantages. The whole machine is visible in seven lines, so a reviewer can compare it with the diagram at a glance. And because it is data, you can generate the diagram from it or test it exhaustively by iterating over every (status, event) pair.
Its weakness appears the moment transitions need behaviour. "Cancelling a paid order issues a refund" is not a status change; it is an action attached to one transition. You can grow the table to hold actions and guards ((PAID, CANCEL) -> CANCELLED, action = refund, guard = notShipped), and many state machine libraries do exactly that. But once most rows carry their own logic, you have rebuilt State classes in a less type-safe form, and it is time to switch.
Enum switch vs transition table vs State classes
Interviewers care most about this trade-off, because it shows whether you choose patterns or just recognise them.
| Concern | Enum + switch | Transition table | State classes |
|---|---|---|---|
| Adding a state | Touch every method that switches | Add rows | Add one class |
| Adding an event | Add one method with a switch | Add rows | Touch the interface, plus the states that handle it |
| Seeing the whole machine | Hard; read every method | Easy; it's one table | Medium; read every class, or keep a diagram |
| Per-state behaviour | Inline in each case | Needs an action column | Natural; it's a method |
| Per-state data | Fields on the context, valid only in some states | Same | Fields on the context, or on fresh state objects |
| Compile-time completeness | Java switch expressions and TS never checks catch missing cases | None by default; test it | Abstract methods force every pair to be handled |
| Serialising the state | Trivial (store the enum) | Trivial | Store a name, map it back to an object on load |
| Ceremony for 3 states | Lowest | Low | Highest |
Rules of thumb:
- Few states, little behaviour, stable set: enum and
switch. Use a switch expression or a TypeScriptnevercheck so a new constant breaks the build. - Behaviour is mostly "is this transition allowed?": transition table. Order, ticket and document workflows.
- Each state has its own rules for several events: State classes. Vending machines, ATMs, connections, game characters.
- States added more often than events? Classes win. Events added more often? The switch wins. It's the expression problem again, which the Visitor page covers from the other side.
There is a useful middle ground in Java: an enum with constant-specific methods. Each constant gets its own body, so behaviour stays grouped by state, but you keep the enum's free serialisation, values() iteration and EnumMap support.
public class TrafficLight {
enum Light {
RED { Light next() { return GREEN; } int seconds() { return 30; } },
GREEN { Light next() { return AMBER; } int seconds() { return 25; } },
AMBER { Light next() { return RED; } int seconds() { return 5; } };
abstract Light next();
abstract int seconds();
}
public static void main(String[] args) {
Light light = Light.RED;
int total = 0;
for (int i = 0; i < 3; i++) { total += light.seconds(); light = light.next(); }
assert light == Light.RED && total == 60;
System.out.println("traffic light: all assertions passed");
}
}
The limits: constants can't see instance data unless you pass the context in, and other modules can't add states. For a small closed set, it's often the best of both worlds.
Variations worth knowing
States that carry data. A tracking number exists only once an order has shipped. As a context field it is null most of the time. A TypeScript discriminated union ({ status: "shipped"; tracking: string } | ...) or Java 21 sealed records make the data part of the state, so the compiler stops you reading tracking from a paid order. That's the reducer style the behavioral patterns overview shows as the functional alternative.
Entry and exit actions. "On entering Maintenance, lock the coin slot" belongs in an onEnter(m) hook called from setState, not copied into every transition that leads there.
Persisted state machines. Store the state's name, not the object, and map it back to the instance on load. Concurrent updates need optimistic locking (UPDATE ... WHERE id = ? AND status = 'PAID'), because two servers can load the same order and try different transitions.
Real-world uses
- Network protocol implementations. A TCP connection moves through states named in its specification (LISTEN, SYN-SENT, ESTABLISHED and others), and the same segment means different things in each. It's the textbook example, though real network stacks use switches and tables, not a class per state.
- Java's thread lifecycle.
java.lang.Thread.Stateis an enum withNEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITINGandTERMINATED. It's a state machine exposed as an enum, a good reminder that not every state machine needs State classes. - Promises in JavaScript. A promise is pending, fulfilled or rejected, and calling
resolveon a settled promise does nothing: a terminal state ignoring events. - State machine libraries. Spring Statemachine (Java), XState (JavaScript and TypeScript) and
transitions(Python) let you declare states, events, guards and actions as configuration. They are the transition-table approach grown up, and worth naming in an interview when the machine is large or needs visualising. - UI components. Media players, form wizards and drag-and-drop interactions are small state machines, often written with React's
useReduceras a reducer over a state union.
When NOT to use it
- Two or three states with trivial behaviour. A
boolean isOpenor a three-value enum with one switch is clearer than an interface and three classes. The pattern pays for itself when the per-state logic is substantial or the number of states grows. - States that differ only in which transitions are legal. Use a transition table. Classes with empty bodies that exist only to return the next state are noise.
- When events change more often than states. Five fixed states and a new operation every sprint favour the switch-per-event layout.
- When operators configure the workflow. The transitions must live in a table or configuration, not in compiled classes.
- When the "state" is really a set of independent flags. A user who can be verified or not, premium or not, and suspended or not has eight combinations. Turning that into eight State classes is a mistake; those are three independent properties. State machines model mutually exclusive modes.
The cost is class count and indirection: "what does select do?" means opening several files. Keep a state diagram next to the code.
Related patterns
Strategy. Nearly identical class diagrams; the difference is who chooses the implementation. A strategy is chosen by the client for a reason outside the object ("this customer gets volume pricing") and usually stays fixed. A state is chosen by the object itself as events happen, and changes all the time. Strategies don't know about each other; states usually name their successors. If the "strategy" swaps itself after every call, you've written State.
Command. Events delivered to a state machine are often commands. A queue of commands feeding a state machine is a common architecture for devices and games, and recording the commands gives you replay.
Memento. To undo a transition, snapshot the context (state name plus data) before applying the event. Memento is how you would add "undo the last action" to a state machine without exposing its internals.
Flyweight and Singleton. Stateless states can be shared, as in this page's INSTANCE fields. This is safe because they are immutable.
Observer. Systems often need to react to transitions: send an email when an order ships, update a dashboard when a machine sells out. Publishing a "state changed" event from setState keeps those side effects out of the states.
The smell that suggests it
- The same
switch(orif/elifchain) on the same status field appears in several methods. This is the main signal. - Methods that begin with a guard on the status:
if (status != PAID) throw ..., repeated with different statuses in each method. - Comments such as "only valid when..." on fields or methods.
- Bugs where an operation ran in the wrong mode, such as refunding an order that was never paid.
- A feature request that adds a mode, and you realise it touches every method in the class.
- Boolean flags that should be mutually exclusive but aren't enforced:
isPaid,isShippedandisCancelledon the same object, where nothing stops all three from being true.
Interview questions
-
"What's the difference between State and Strategy? They have the same diagram." The structure is the same; the intent and the control flow differ. A strategy is picked by the client and represents how to do something. A state is changed by the object as events happen and represents what mode the object is in. States usually know their successors; strategies are independent of each other.
-
"Who should perform the transition: the context or the state?" Either works. States calling
setStatekeeps each transition next to the logic that causes it. The context deciding (via a returned state or a table) centralises the machine and decouples the states. I default to states for small machines and a table for large ones. -
"Your state classes are singletons. Isn't Singleton an anti-pattern?" The problem with Singleton is global mutable state and hidden dependencies. These state objects have no fields, so sharing them is like sharing a constant. If a state needed its own data, I'd create a new instance per transition or keep the data on the context.
-
"How do you make this thread-safe?" Each event is a check-then-act on shared data, so the whole event must be atomic. I lock in the context's public methods. The states never lock, because they always run inside that lock. If the machine is persisted, I use optimistic concurrency: the update includes the expected current state in its
WHEREclause. -
"When would you use an enum and a switch instead?" When there are few states, little per-state behaviour, and the set is stable. Or when operations are added more often than states. I'd use a switch expression or an exhaustiveness check so that adding a constant fails the build.
-
"How do you test a state machine?" For each state, fire each event and assert the resulting state and side effects. Test illegal transitions too, because those are the bugs that cost money. A table makes this exhaustive: loop over every pair.
-
"The interviewer adds a maintenance mode. What changes?" One new state class, one new event on the interface (the service key), and one decision about money already inserted, which goes into
HasMoney. Existing states don't change. That is the extensibility argument for the pattern, so I'd say it out loud. -
"Where does logging or notifying on transitions go?" In one place:
setStatein the context. Call anonTransition(from, to)hook or publish an event there. Putting it in every state duplicates it and makes it easy to miss a transition.
Further reading
- Behavioral patterns overview: the short version, plus the reducer-based functional alternative.
- Vending machine case study: this pattern applied in a full LLD interview answer.
- ATM machine case study: another device driven by states, combined with a chain of handlers.
- UML for interviews: when to draw a state diagram instead of a class diagram.
- Common LLD mistakes: the leaky-enum smell that usually leads to this pattern.
- Pattern selection guide: State next to the patterns it is most often confused with.