State pattern
Give each state of an object its own class so behaviour and transitions live in one place. An order lifecycle in full Java and Python, versus switch statements and Strategy.
On this page
The problem: the same switch in every method
An online shop's order goes through a lifecycle: it is placed, then paid, shipped and delivered, and it can be cancelled before it ships. The first version stores the status in an enum field and checks it in every method:
enum Status { PLACED, PAID, SHIPPED, DELIVERED, CANCELLED }
void cancel() {
switch (status) {
case PLACED -> status = Status.CANCELLED;
case PAID -> { refund(); status = Status.CANCELLED; }
case SHIPPED, DELIVERED, CANCELLED -> throw new IllegalStateException("too late");
}
}
void ship(String tracking) {
switch (status) {
case PAID -> { this.tracking = tracking; status = Status.SHIPPED; }
default -> throw new IllegalStateException("cannot ship when " + status);
}
}
// pay() and deliver() have their own switch, too
With five statuses and four events this is still readable. Then the business adds ON_HOLD (a fraud check that freezes a paid order) and RETURNED. Each new status means editing every method's switch, and the rules for "what can a paid order do?" are spread across four methods. Forget one case and an order on hold can be shipped.
Every method switches on the status
- The naive version stores a status field and puts a switch in every method. Each new state, say “flashing yellow at night”, means editing every one of those switches.
The underlying issue: the object's behaviour depends on its state, and the rules for each state are scattered by event instead of grouped by state.
The idea: one class per state
A state machine is a set of states, the events that can happen, and the transitions: for each state, which events are allowed and which state comes next. The State pattern turns each state into a class. The object that has the lifecycle, the context, holds its current state object and forwards every event to it. The state decides what to do and which state comes next.
The context forwards each event to its current state
- The State pattern gives each state its own class. The TrafficLight, the context, holds its current state object and passes every event to it. Each state decides what to do, and which state comes next.
- Each state class is short and holds all the rules for that one state. The light itself never asks “what colour am I?”: it just forwards the call.
The animation uses a traffic light, the smallest state machine there is; the order below has the same shape.
| Role | In this example | Responsibility |
|---|---|---|
| Context | Order | Holds the current state; its public methods delegate to it; exposes setState to the states |
| State (interface) | OrderState | One method per event: pay, ship, deliver, cancel |
| Concrete states | Placed, Paid, Shipped, Delivered, Cancelled | The rules for one state, including the transition to the next |
Before writing code, draw the machine. Interviewers like to see this table, because it shows every legal move and every refusal at a glance:
| State | pay | ship | deliver | cancel |
|---|---|---|---|---|
| PLACED | → PAID | refuse | refuse | → CANCELLED |
| PAID | refuse | → SHIPPED | refuse | refund → CANCELLED |
| SHIPPED | refuse | refuse | → DELIVERED | refuse |
| DELIVERED | refuse | refuse | refuse | refuse |
| CANCELLED | refuse | refuse | refuse | refuse |
DELIVERED and CANCELLED are terminal states: nothing leaves them.
An order is a state machine too
- Adding night mode is now one new class, NightState, with its own rules. Vending machines, order status (placed, paid, shipped), media players and game characters are all state machines that fit this pattern.
Build it step by step
1. The state interface. One method per event. Java's default methods (and a Python base class) make every event refuse by default, so each state only writes the events it allows. A new event is added once, in the interface, and is safely refused everywhere until someone decides otherwise.
2. One class per state. Each holds all the rules for that state, and performs its own transitions by calling order.setState(...).
3. The context. Its public methods forward to the current state and never switch. setState is package-private (in Python, a convention), because only states should move the order.
4. The client just calls pay, ship and so on, and gets an exception for an illegal move.
import java.util.*;
// ---------- Client ----------
public class OrderDemo {
public static void main(String[] args) {
Order a = new Order("A-1", 4999);
a.pay(4999); a.ship("TRK-77"); a.deliver();
System.out.println(a.id + ": " + a.history());
Order b = new Order("B-2", 1500);
b.pay(1500); b.cancel(); // paid, so cancelling refunds
System.out.println(b.id + ": " + b.history());
Order c = new Order("C-3", 800);
try { c.ship("TRK-78"); } // not paid yet
catch (IllegalStateException e) { System.out.println(c.id + ": " + e.getMessage()); }
try { a.cancel(); }
catch (IllegalStateException e) { System.out.println(a.id + ": " + e.getMessage()); }
}
}
// ---------- 1. The state interface: every event, refused by default ----------
interface OrderState {
String name();
default void pay(Order o, long cents) { refuse(o, "pay"); }
default void ship(Order o, String tracking) { refuse(o, "ship"); }
default void deliver(Order o) { refuse(o, "deliver"); }
default void cancel(Order o) { refuse(o, "cancel"); }
private void refuse(Order o, String event) {
throw new IllegalStateException("cannot " + event + " an order that is " + name());
}
}
// ---------- 2. Concrete states: each overrides only the events it allows ----------
final class Placed implements OrderState {
public String name() { return "PLACED"; }
public void pay(Order o, long cents) {
if (cents != o.totalCents) throw new IllegalArgumentException("expected " + o.totalCents + " cents");
o.setState(new Paid());
}
public void cancel(Order o) { o.setState(new Cancelled()); }
}
final class Paid implements OrderState {
public String name() { return "PAID"; }
public void ship(Order o, String tracking) { o.tracking = tracking; o.setState(new Shipped()); }
public void cancel(Order o) { o.refund(); o.setState(new Cancelled()); }
}
final class Shipped implements OrderState {
public String name() { return "SHIPPED"; }
public void deliver(Order o) { o.setState(new Delivered()); }
}
final class Delivered implements OrderState { public String name() { return "DELIVERED"; } }
final class Cancelled implements OrderState { public String name() { return "CANCELLED"; } }
// ---------- 3. The context ----------
final class Order {
final String id; final long totalCents;
String tracking;
private OrderState state = new Placed();
private final List<String> history = new ArrayList<>(List.of("PLACED"));
Order(String id, long totalCents) { this.id = id; this.totalCents = totalCents; }
// Public API: delegate, never switch
public synchronized void pay(long cents) { state.pay(this, cents); }
public synchronized void ship(String tracking) { state.ship(this, tracking); }
public synchronized void deliver() { state.deliver(this); }
public synchronized void cancel() { state.cancel(this); }
public synchronized String status() { return state.name(); }
public synchronized List<String> history() { return List.copyOf(history); }
// Called only by states (package-private)
void setState(OrderState next) { state = next; history.add(next.name()); }
void refund() { history.add("refund " + totalCents); }
}import threading
# ---------- 1. The state base class: every event, refused by default ----------
class OrderState:
name = "?"
def pay(self, order, cents):
self._refuse("pay")
def ship(self, order, tracking):
self._refuse("ship")
def deliver(self, order):
self._refuse("deliver")
def cancel(self, order):
self._refuse("cancel")
def _refuse(self, event):
raise RuntimeError(f"cannot {event} an order that is {self.name}")
# ---------- 2. Concrete states: each overrides only the events it allows ----------
class Placed(OrderState):
name = "PLACED"
def pay(self, order, cents):
if cents != order.total_cents:
raise ValueError(f"expected {order.total_cents} cents")
order.set_state(Paid())
def cancel(self, order):
order.set_state(Cancelled())
class Paid(OrderState):
name = "PAID"
def ship(self, order, tracking):
order.tracking = tracking
order.set_state(Shipped())
def cancel(self, order):
order.refund()
order.set_state(Cancelled())
class Shipped(OrderState):
name = "SHIPPED"
def deliver(self, order):
order.set_state(Delivered())
class Delivered(OrderState):
name = "DELIVERED"
class Cancelled(OrderState):
name = "CANCELLED"
# ---------- 3. The context ----------
class Order:
def __init__(self, id, total_cents):
self.id, self.total_cents = id, total_cents
self.tracking = None
self._state = Placed()
self._history = ["PLACED"]
self._lock = threading.Lock()
# Public API: delegate, never switch
def pay(self, cents):
with self._lock: self._state.pay(self, cents)
def ship(self, tracking):
with self._lock: self._state.ship(self, tracking)
def deliver(self):
with self._lock: self._state.deliver(self)
def cancel(self):
with self._lock: self._state.cancel(self)
@property
def status(self):
return self._state.name
def history(self):
return list(self._history)
# Called only by states
def set_state(self, nxt):
self._state = nxt
self._history.append(nxt.name)
def refund(self):
self._history.append(f"refund {self.total_cents}")
# ---------- Client ----------
if __name__ == "__main__":
a = Order("A-1", 4999)
a.pay(4999); a.ship("TRK-77"); a.deliver()
print(f"{a.id}: [{', '.join(a.history())}]")
b = Order("B-2", 1500)
b.pay(1500); b.cancel() # paid, so cancelling refunds
print(f"{b.id}: [{', '.join(b.history())}]")
c = Order("C-3", 800)
try:
c.ship("TRK-78") # not paid yet
except RuntimeError as e:
print(f"{c.id}: {e}")
try:
a.cancel()
except RuntimeError as e:
print(f"{a.id}: {e}")Both print:
A-1: [PLACED, PAID, SHIPPED, DELIVERED]
B-2: [PLACED, PAID, refund 1500, CANCELLED]
C-3: cannot ship an order that is PLACED
A-1: cannot cancel an order that is DELIVERED
Three details worth pointing out in an interview:
- The rules for "paid" are in one class. Cancelling a paid order refunds it; cancelling a placed one doesn't. Nobody has to read four switches to find that out.
- The context's methods are synchronized (a lock in Python). An event is a read-decide-write sequence; without the lock,
ship()andcancel()on two threads could both see PAID and both succeed. - States here carry no data, so they could be shared singletons (
Paid.INSTANCE) instead ofnew Paid()each time. Data that belongs to the order, such as the tracking number, lives on the order.
Adding a state touches one place
The fraud team wants ON_HOLD: a paid order can be put on hold, and a held order can only be released (back to PAID) or cancelled with a refund. That is one new class, OnHold, plus one new line in Paid (hold() moves to OnHold) and a hold/release event in the interface that every other state refuses by default. Placed, Shipped and Delivered are not opened. Compare that with editing every switch in the first version.
Who decides the next state?
Two common choices, and an interviewer may ask which you'd pick:
- The states decide (as above). Each state knows its successors. The rules are local and easy to read, but the states know about each other, so the full map of transitions is spread across classes.
- The context or a table decides. States only do the work; the context looks up
(state, event) → next statein one table. The whole machine is visible in one place and easy to validate or draw, but per-state behaviour (refunds, emails) needs a separate hook.
For a lifecycle that is mostly transitions with little behaviour, the table on its own is often the best answer, and it is short enough to show in full:
import java.util.*;
public class TableDemo {
enum Status { PLACED, PAID, SHIPPED, DELIVERED, CANCELLED }
enum Event { PAY, SHIP, DELIVER, CANCEL }
// The whole state machine as data: (status, event) -> next status
static final Map<Status, Map<Event, Status>> NEXT = Map.of(
Status.PLACED, Map.of(Event.PAY, Status.PAID, Event.CANCEL, Status.CANCELLED),
Status.PAID, Map.of(Event.SHIP, Status.SHIPPED, Event.CANCEL, Status.CANCELLED),
Status.SHIPPED, Map.of(Event.DELIVER, Status.DELIVERED));
static Status fire(Status s, Event e) {
Status next = NEXT.getOrDefault(s, Map.of()).get(e);
if (next == null) throw new IllegalStateException("cannot " + e + " when " + s);
return next;
}
public static void main(String[] args) {
Status s = Status.PLACED;
for (Event e : List.of(Event.PAY, Event.SHIP, Event.DELIVER)) s = fire(s, e);
System.out.println(s); // DELIVERED
try { fire(Status.SHIPPED, Event.CANCEL); }
catch (IllegalStateException ex) { System.out.println(ex.getMessage()); }
}
}from enum import Enum
class Status(Enum):
PLACED = 1
PAID = 2
SHIPPED = 3
DELIVERED = 4
CANCELLED = 5
# The whole state machine as data: (status, event) -> next status
NEXT = {
(Status.PLACED, "pay"): Status.PAID,
(Status.PLACED, "cancel"): Status.CANCELLED,
(Status.PAID, "ship"): Status.SHIPPED,
(Status.PAID, "cancel"): Status.CANCELLED,
(Status.SHIPPED, "deliver"): Status.DELIVERED,
}
def fire(status, event):
try:
return NEXT[(status, event)]
except KeyError:
raise RuntimeError(f"cannot {event} when {status.name}") from None
s = Status.PLACED
for e in ("pay", "ship", "deliver"):
s = fire(s, e)
print(s.name) # DELIVERED
try:
fire(Status.SHIPPED, "cancel")
except RuntimeError as ex:
print(ex)State versus a switch on an enum
The State pattern is not automatically better than an enum. Choose by what grows:
| Switch on an enum | Transition table | State classes | |
|---|---|---|---|
| Good at | Tiny machines; everything visible in one method | The whole machine as data: easy to draw, validate, store in config | Rich per-state behaviour; adding states without editing others |
| Weak at | Each new state edits every switch | Per-state behaviour needs extra code | Many small classes; the full map is spread out |
| Use when | 2–4 states, few events, rarely changes | Many states, little behaviour per transition (workflow, ticket status) | States behave very differently (vending machine, TCP connection, game character) |
Modern Java narrows the gap: a switch expression over an enum or a sealed interface (Java 21) gives a compile error when a case is missing, so "forgot to handle ON_HOLD" is caught by the compiler. Java enums can also carry per-constant methods (PAID { void cancel(Order o) { … } }), which is the State pattern without separate files. In Python 3.10+, match on an enum is the switch equivalent, but nothing checks that it is exhaustive unless you use a type checker.
State, Strategy, Command: how they differ
All three put behaviour in an object behind an interface. See Strategy and Command for the full patterns.
| State | Strategy | Command | |
|---|---|---|---|
| What varies | Behaviour, depending on the object's current mode | The algorithm for one job | Nothing: it packages a request |
| Who swaps it | The object itself (usually the states) as events arrive | The client, from outside | Not swapped; created, queued, run, maybe undone |
| Do variants know each other? | Usually: a state names the next state | No | No |
| Lifetime | Replaced on every transition | Often fixed for the context's life | One per request |
| Example | Order: PLACED → PAID → SHIPPED | Pay by card, PayPal or UPI | "Ship order 42", logged and retried |
The one-line test: if the variants replace each other on their own, it's State; if the caller picks one, it's Strategy.
When not to use it
Where you meet it in real code
- TCP connections: the original Gang of Four example (
TCPConnectionwithTCPEstablished,TCPListen,TCPClosed). The real protocol has about a dozen states. - Media players: Android's
MediaPlayerdocuments a state diagram (Idle, Prepared, Started, Paused, Stopped) and throwsIllegalStateExceptionfor a call in the wrong state, the same refuse-by-default idea. - Libraries: Spring Statemachine (Java),
transitions(Python) and XState (JavaScript) let you declare states and transitions, then add guards and actions. - Workflows: AWS Step Functions and order or payment services model each lifecycle as a state machine stored in the database.
- Games: enemy AI (patrol, chase, attack, flee) is a classic State-pattern use.
In the interview
A publishing tool has documents that are Draft, In review or Published. Authors can edit only drafts and submit a draft for review. A reviewer can approve (→ Published) or reject (→ Draft, with a comment). Publishing sends an email to subscribers. Draw the state-by-event table, then sketch the state interface and the InReview class.
Compare with our answer
| State | edit | submit | approve | reject |
|---|---|---|---|---|
| Draft | allowed | → In review | refuse | refuse |
| In review | refuse | refuse | → Published, email | → Draft, store comment |
| Published | refuse | refuse | refuse | refuse |
interface DocState {
String name();
default void edit(Document d, String text) { throw refuse("edit"); }
default void submit(Document d) { throw refuse("submit"); }
default void approve(Document d) { throw refuse("approve"); }
default void reject(Document d, String comment) { throw refuse("reject"); }
private IllegalStateException refuse(String e) { return new IllegalStateException("cannot " + e + " when " + name()); }
}
final class InReview implements DocState {
public String name() { return "IN_REVIEW"; }
public void approve(Document d) { d.setState(new Published()); d.notifySubscribers(); }
public void reject(Document d, String comment) { d.addComment(comment); d.setState(new Draft()); }
}class DocState:
name = "?"
def edit(self, doc, text): self._refuse("edit")
def submit(self, doc): self._refuse("submit")
def approve(self, doc): self._refuse("approve")
def reject(self, doc, comment): self._refuse("reject")
def _refuse(self, event):
raise RuntimeError(f"cannot {event} when {self.name}")
class InReview(DocState):
name = "IN_REVIEW"
def approve(self, doc):
doc.set_state(Published())
doc.notify_subscribers()
def reject(self, doc, comment):
doc.add_comment(comment)
doc.set_state(Draft())A strong answer mentions: the table drawn first, including the refusals · events refused by default in the interface · the email sent by the transition into Published, not by the caller · the reject comment stored on the document (state classes hold no document data) · who is allowed to approve is a permission check, not a state (the reviewer role is checked before the event reaches the state).
- Intent: an object changes its behaviour when its internal state changes; each state is a class.
- Roles: context (holds the current state, delegates) · State interface (one method per event) · concrete states (rules + transitions).
- Draw the table first: states × events, with every refusal; mark terminal states.
- Refuse by default in the interface, so a new event is safe everywhere.
- Transitions: states call
setState(local rules) or one table decides (whole map in one place). - Persistence: store the status string; rebuild the state object on load; conditional
UPDATE … WHERE status = ?across servers. - Versus switch: fine for tiny machines, and exhaustive in Java 21; State wins when per-state behaviour is rich.
- Versus Strategy: states swap themselves; a strategy is chosen by the caller.
The shop adds two rules: a delivered order can be returned within 30 days, which refunds it; and an order still PLACED after 24 hours without payment is cancelled automatically. How does the design change, and what new problem appears?
Compare with our answer
A strong answer mentions: a new Returned state and a requestReturn(order, now) event that Delivered implements and every other state refuses · the 30-day rule checked inside Delivered using a delivery timestamp stored on the order and a time passed in (testable) · the auto-cancel driven by a scheduled job or delayed message that fires a normal cancel event, not by code that writes the status directly · that job racing a late payment, so the transition must be atomic (UPDATE … WHERE status = 'PLACED') and the loser handled (refund a payment that arrives after cancellation) · Delivered stops being terminal, so check anything that assumed it was (reports, archiving).
1. An order service stores the status in an enum and has a switch in pay(), ship(), cancel() and deliver(). The team must add ON_HOLD and RETURNED. What is the strongest argument for moving to the State pattern?
The pain is that rules are grouped by event, not by state, so each new state touches every method. Persistence still needs the status column, and performance is not the issue.
2. In the order example, who performs the transition from PAID to SHIPPED?
With the states-decide variant, each state performs its own transitions. If the client set states directly, nothing would stop illegal moves; a switch on the state's class brings back the original problem.
3. Two application servers handle "ship" and "cancel" for the same PAID order at the same moment. Each loads the order and runs the State pattern correctly. What prevents both from succeeding?
Locks and singletons live inside one process. The database must pick the winner: the conditional update changes one row for the first request and zero for the second, which then reloads and is refused.
4. Which design fits best for an IT ticketing system with 15 statuses whose only difference is which transitions are allowed?
When states carry little behaviour, the machine is data. A table is short, visible in one place and easy to validate; fifteen near-empty classes add ceremony without benefit.
5. What is the main difference between State and Strategy?
Both use composition and look identical on a class diagram. The difference is who triggers the change: states transition themselves, strategies are picked from outside.
6. A new event, requestInvoice(), is added to OrderState. Only PAID and DELIVERED orders may request an invoice. With refuse-by-default in the interface, what has to change?
The default refusal means a new event is safe everywhere until a state opts in. Putting the check in the context or the client scatters the rules again.
7. A candidate's Paid.cancel() calls paymentService.refund() and then order.setState(new Cancelled()). The request times out after the refund and the client retries. What goes wrong?
The side effect happened but the transition was not recorded. Record the transition and the refund request together (an outbox), or make the refund idempotent with a key such as the order id.
Score 60% or more and the lesson is marked complete.