Patterns for behaviour · Chapter 18

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.

IntermediateInterview priority: High45 min
On this page
  1. The problem: the same switch in every method
  2. The idea: one class per state
  3. Build it step by step
  4. Who decides the next state?
  5. State versus a switch on an enum
  6. State, Strategy, Command: how they differ
  7. When not to use it
  8. Where you meet it in real code
  9. In the interview
  10. Quiz

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

  1. 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

  1. 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.
  2. 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.

RoleIn this exampleResponsibility
ContextOrderHolds the current state; its public methods delegate to it; exposes setState to the states
State (interface)OrderStateOne method per event: pay, ship, deliver, cancel
Concrete statesPlaced, Paid, Shipped, Delivered, CancelledThe 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:

Statepayshipdelivercancel
PLACED→ PAIDrefuserefuse→ CANCELLED
PAIDrefuse→ SHIPPEDrefuserefund → CANCELLED
SHIPPEDrefuserefuse→ DELIVEREDrefuse
DELIVEREDrefuserefuserefuserefuse
CANCELLEDrefuserefuserefuserefuse

DELIVERED and CANCELLED are terminal states: nothing leaves them.

An order is a state machine too

  1. 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); }
}

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() and cancel() on two threads could both see PAID and both succeed.
  • States here carry no data, so they could be shared singletons (Paid.INSTANCE) instead of new 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 state in 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()); }
    }
}

State versus a switch on an enum

The State pattern is not automatically better than an enum. Choose by what grows:

Switch on an enumTransition tableState classes
Good atTiny machines; everything visible in one methodThe whole machine as data: easy to draw, validate, store in configRich per-state behaviour; adding states without editing others
Weak atEach new state edits every switchPer-state behaviour needs extra codeMany small classes; the full map is spread out
Use when2–4 states, few events, rarely changesMany 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.

StateStrategyCommand
What variesBehaviour, depending on the object's current modeThe algorithm for one jobNothing: it packages a request
Who swaps itThe object itself (usually the states) as events arriveThe client, from outsideNot swapped; created, queued, run, maybe undone
Do variants know each other?Usually: a state names the next stateNoNo
LifetimeReplaced on every transitionOften fixed for the context's lifeOne per request
ExampleOrder: PLACED → PAID → SHIPPEDPay 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 (TCPConnection with TCPEstablished, TCPListen, TCPClosed). The real protocol has about a dozen states.
  • Media players: Android's MediaPlayer documents a state diagram (Idle, Prepared, Started, Paused, Stopped) and throws IllegalStateException for 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

Your turn: a document workflow

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
Stateeditsubmitapprovereject
Draftallowed→ In reviewrefuserefuse
In reviewrefuserefuse→ Published, email→ Draft, store comment
Publishedrefuserefuserefuserefuse
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()); }
}

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).

State on one page
  • 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.
Your turn: the requirement changes

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).

Interactive labPractise it: run the traffic light, then add night modeOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

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?

2. In the order example, who performs the transition from PAID to SHIPPED?

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?

4. Which design fits best for an IT ticketing system with 15 statuses whose only difference is which transitions are allowed?

5. What is the main difference between State and Strategy?

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?

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?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.