LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 36 OF 48

State Pattern in Java: One Class per State, Not a Big Switch

The State pattern with a ride booking example: why a status enum with a switch in every method breaks down, one class per state, the context that delegates, who owns transitions, the transition table, terminal states, stateless states as shared instances, how State differs from Strategy and from a plain switch, and where it shows up in LLD interviews.

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

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

Java example

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

import java.util.ArrayList;
import java.util.List;

/** State pattern: a ride behaves differently in each stage of its life. */
public class RideLifecycle {

    // ---------- 1. The problem: one switch per method ----------
    enum RideStatus { SEARCHING, ASSIGNED, ON_TRIP, FINISHED, CANCELLED }

    static final class SwitchyRide {
        RideStatus status = RideStatus.ASSIGNED;
        int fee;

        String cancel() {
            // The same switch appears again in assignDriver, startTrip and endTrip.
            switch (status) {
                case SEARCHING -> status = RideStatus.CANCELLED;
                case ASSIGNED -> {
                    fee = 50;
                    status = RideStatus.CANCELLED;
                }
                case ON_TRIP -> {
                    return "refused: end the trip instead";
                }
                default -> {
                    return "refused: ride is over";
                }
            }
            return "cancelled, fee " + fee;
        }
    }

    // ---------- 2. The clean version ----------

    /** One method per action. Defaults refuse, so each state overrides only what it allows. */
    interface RideState {
        String label();

        default void assignDriver(Ride ride, String driver) { ride.refuse("assign a driver"); }

        default void startTrip(Ride ride) { ride.refuse("start the trip"); }

        default void endTrip(Ride ride, int km) { ride.refuse("end the trip"); }

        default void cancel(Ride ride) { ride.refuse("cancel"); }
    }

    static final int CANCEL_FEE = 50;
    static final int BASE_FARE = 60;
    static final int PER_KM = 14;

    static final class Searching implements RideState {
        @Override
        public String label() { return "searching"; }

        @Override
        public void assignDriver(Ride ride, String driver) {
            ride.setDriver(driver);
            ride.moveTo(new DriverAssigned());
        }

        @Override
        public void cancel(Ride ride) { ride.moveTo(new Cancelled()); } // free before a driver is found
    }

    static final class DriverAssigned implements RideState {
        @Override
        public String label() { return "driver on the way"; }

        @Override
        public void startTrip(Ride ride) { ride.moveTo(new OnTrip()); }

        @Override
        public void cancel(Ride ride) {
            ride.charge(CANCEL_FEE);
            ride.moveTo(new Cancelled());
        }
    }

    static final class OnTrip implements RideState {
        @Override
        public String label() { return "on trip"; }

        @Override
        public void endTrip(Ride ride, int km) {
            ride.charge(BASE_FARE + km * PER_KM);
            ride.moveTo(new Finished());
        }

        @Override
        public void cancel(Ride ride) { ride.refuse("cancel; end the trip instead"); }
    }

    /** Terminal states override nothing: every action is refused by the defaults. */
    static final class Finished implements RideState {
        @Override
        public String label() { return "finished"; }
    }

    static final class Cancelled implements RideState {
        @Override
        public String label() { return "cancelled"; }
    }

    /** The context: holds the data, delegates every action to the current state. */
    static final class Ride {
        private final String id;
        private RideState state = new Searching();
        private String driver = "none";
        private int charged;
        private final List<String> log = new ArrayList<>();

        Ride(String id) { this.id = id; }

        // public API: pure delegation
        void assignDriver(String name) { state.assignDriver(this, name); }

        void startTrip() { state.startTrip(this); }

        void endTrip(int km) { state.endTrip(this, km); }

        void cancel() { state.cancel(this); }

        // helpers the states use
        void moveTo(RideState next) {
            log.add(state.label() + " -> " + next.label());
            System.out.println("  " + id + ": " + state.label() + " -> " + next.label());
            state = next;
        }

        void setDriver(String name) { driver = name; }

        void charge(int amount) {
            charged += amount;
            System.out.println("  " + id + ": charged " + amount);
        }

        void refuse(String action) {
            System.out.println("  " + id + ": cannot " + action + " (state: " + state.label() + ")");
        }

        String summary() {
            return id + " driver=" + driver + " state=" + state.label()
                + " charged=" + charged + " steps=" + log;
        }
    }

    public static void main(String[] args) {
        System.out.println("Problem: a switch in every method");
        System.out.println("  " + new SwitchyRide().cancel());

        System.out.println();
        System.out.println("State pattern: a full trip");
        Ride trip = new Ride("R1");
        trip.startTrip();          // refused: no driver yet
        trip.assignDriver("driver-17");
        trip.startTrip();
        trip.cancel();             // refused while on trip
        trip.endTrip(12);          // fare 60 + 12 * 14 = 228
        trip.cancel();             // refused: finished is terminal
        System.out.println("  " + trip.summary());

        System.out.println("Cancel after a driver is assigned");
        Ride late = new Ride("R2");
        late.assignDriver("driver-42");
        late.cancel();             // fee 50
        System.out.println("  " + late.summary());

        System.out.println("Cancel while searching");
        Ride early = new Ride("R3");
        early.cancel();            // free
        System.out.println("  " + early.summary());
    }
}

Notes

The problem

Here is the naive version. The ride has a status enum, and every method switches on it. Cancel has one switch, assign driver has another, start trip another, end trip another. The rules for one situation, say driver assigned, are scattered across four methods. When product adds a new status, like driver arrived, you must find and edit every switch, and missing one branch is a silent bug.

The naive version
void cancel() {
    switch (status) {
      case SEARCHING -> status = CANCELLED;
      case ASSIGNED -> { fee = 50;
          status = CANCELLED; }
      case ON_TRIP -> fail("end trip");
      default -> fail("already over");
    }
}
// assignDriver, startTrip, endTrip:
// the same switch, four times

The idea

The idea in one sentence: put the behaviour for each situation in its own class, and let the object delegate every call to whichever one is current. When the situation changes, the object swaps in a different state object. From the outside it looks as if the ride changed its class: the same method call now behaves completely differently. Instead of grouping code by method, we group it by situation.

In one sentence
  • put the behaviour for each
  • situation in its own class,
  • and let the object delegate to
  • whichever one is current
  • from outside, the object seems
  • to change its class when its
  • situation changes

The structure

The participants. RiderApp is the client that taps buttons. Ride is the context: it holds the trip details and a reference to its current state. RideState is the state interface, with one method per action: assign driver, start trip, end trip and cancel. Searching, DriverAssigned, OnTrip, Finished and Cancelled are the concrete states. The client only ever talks to the ride. It never sees the state classes.

Transition table

Before writing classes, write the transition table. Searching plus assign driver moves to driver assigned. Searching plus cancel is free. Driver assigned plus start trip moves to on trip, and cancel there costs a fee of fifty. On trip plus end trip charges the fare and moves to finished, and cancel is refused. Finished and cancelled are terminal states that refuse everything. Every cell in this table becomes one method in one class.

Ride transitions
  • Searching + assign -> Assigned
  • Searching + cancel -> Cancelled
  • Assigned + start -> OnTrip
  • Assigned + cancel -> Cancelled
  • (fee 50)
  • OnTrip + end -> Finished
  • (fare by distance)
  • OnTrip + cancel -> refused
  • Finished, Cancelled:
  • terminal, refuse everything

The code: interface

The interface has one method per action, and each method receives the ride. A neat trick: every method has a default body that refuses the action with a clear message. So a state class only overrides the actions it actually allows. The terminal states, finished and cancelled, override nothing at all. Without the defaults, each state would repeat the same boring refusals.

RideState
interface RideState {
    String label();
    default void assignDriver(Ride r,
            String driver) {
        r.refuse("assign a driver"); }
    default void startTrip(Ride r) {
        r.refuse("start the trip"); }
    default void endTrip(Ride r, int km) {
        r.refuse("end the trip"); }
    default void cancel(Ride r) {
        r.refuse("cancel"); }  }

The code: a state

Here is one concrete state, driver assigned. It allows two actions. Start trip moves the ride to on trip. Cancel charges the cancellation fee and moves the ride to cancelled. Everything a developer needs to know about this situation is in one short class. Adding a new rule here cannot break the searching or on trip behaviour, because they live in other files.

DriverAssigned
final class DriverAssigned
        implements RideState {
    public String label() {
        return "driver on the way"; }
    public void startTrip(Ride r) {
        r.moveTo(new OnTrip()); }
    public void cancel(Ride r) {
        r.charge(CANCEL_FEE);
        r.moveTo(new Cancelled()); }
}

The code: context

The context is almost boring, which is the point. The ride starts in searching. Each public method simply forwards to the current state, passing itself. It also offers small helpers the states use, like move to, which logs the transition and swaps the state, and charge, which records money. The ride holds the data. The states hold the rules.

Ride
private RideState state = new Searching();

void cancel() { state.cancel(this); }
void startTrip() { state.startTrip(this); }

void moveTo(RideState next) {
    log(state.label() + " to "
        + next.label());
    state = next;
}

Run-through

Let us follow one ride. The app calls assign driver. The ride forwards it to searching, which records the driver and moves the ride to driver assigned. Next, start trip goes to driver assigned, which moves to on trip. Then end trip with twelve kilometres goes to on trip, which computes the fare and moves to finished. If the app now presses cancel, finished refuses it. The app never wrote a single if statement about status.

Who owns transitions

Who decides the next state? In our version, each state decides, by calling move to. That keeps the rule and the transition together, but states know about each other. The alternative is for the context, or a transition table, to decide, which keeps the whole graph in one place and makes it easy to check. Both are valid designs. In an interview, pick one and say why.

Two choices
  • states decide (our version):
  • + rules and moves together
  • - states know each other
  • context or table decides:
  • + whole graph in one place
  • + easy to draw and verify
  • - rules split from moves
  • both are fine: say which
  • and why

Stateless states

Notice that our state classes have no fields. The driver name and the fare live in the ride. That means one instance of each state can be shared by every ride, as static constants or even as an enum that implements the interface. If a state needs its own data, like a retry counter or a timer, create a fresh instance on every transition instead. Either way, keep the data the whole ride needs in the context.

Sharing state objects
  • our states hold no data:
  • the ride holds driver, fare
  • so one instance each is fine:
  • static final constants,
  • or an enum that implements
  • the interface
  • if a state needs its own data
  • (a timer, a retry count),
  • create a new one each time

State vs switch

Is a switch always wrong? No. With two or three states and one or two actions, a switch expression is shorter and perfectly readable, and adding the State pattern would be over engineering. Move to state classes when there are four or more states, when the rules inside each state keep growing, or when new states arrive often. The cost of the pattern is more classes and logic spread across files, so it must earn its place.

When a switch is fine
  • two or three states
  • one or two actions
  • rules that rarely change
  • move to State classes when:
  • four or more states
  • rules per state are growing
  • new states arrive often
  • Java 17 switch + sealed types
  • keeps small cases readable

State vs Strategy

State and Strategy have the same class diagram: a context holding a reference to an interface. The difference is intent. With Strategy, the client chooses one algorithm, like a fare rule for surge pricing, and it rarely changes during the object's life. The strategies do not know each other. With State, the object switches its own state as events happen, and states often know which state comes next. Ask who changes it and when.

Look alike, differ in intent
  • Strategy: the client picks
  • one algorithm, e.g. a
  • FareRule; it rarely changes
  • and strategies do not know
  • each other
  • State: the object changes its
  • own state as events happen;
  • states often know the next
  • state

In Java and elsewhere

The Java standard library has few textbook examples of this pattern. You meet it in business code instead: order and payment workflows, document review from draft to approved, game characters that idle, run and jump, and network connection handlers. There are also libraries, such as Spring Statemachine, that build the transition graph for you. Do not confuse it with the thread state enum, which only names states and holds no behaviour.

Where you meet it
  • order and payment workflows
  • document review: draft,
  • in review, approved
  • game characters: idle,
  • running, jumping
  • network connection handlers
  • libraries such as Spring
  • Statemachine
  • note: Thread.State is just
  • an enum, not this pattern

In LLD interviews

State is a favourite in machine coding rounds. The vending machine is the classic: idle, has money and maintenance. An elevator moves between idle, moving up, moving down and doors open. An A T M has no card, card inserted and pin verified. Order lifecycles and traffic signals fit too. Listen for words like mode, lifecycle or only allowed when. Draw the transition table on the board first, then name the state classes.

Where it fits
  • vending machine: idle, has
  • money, maintenance
  • elevator: idle, moving up,
  • moving down, doors open
  • ATM: no card, card in, pin ok
  • traffic signal phases
  • order: placed, packed,
  • shipped, delivered
  • parking ticket lifecycle

Mistakes to avoid

Common mistakes. Leaving if statements on status inside the context, which defeats the pattern. Letting states reach into the context's fields instead of calling small helpers. Forgetting to define what happens for an invalid action, so it silently does nothing. Forgetting terminal states, so a finished ride can be cancelled. Using the pattern for two simple states. And skipping the transition table, which is the real specification.

Common mistakes
  • context still checks status
  • with if statements
  • states change fields of the
  • context directly
  • no rule for invalid actions
  • forgetting terminal states
  • state classes for two states
  • not drawing the table first

Interview questions

What is the State pattern?

It moves the behaviour for each situation of an object into its own class behind a common interface. The object, called the context, delegates every call to its current state object and swaps that object when a transition happens, so it appears to change its class.

Why not just use an enum and a switch statement?

For two or three states a switch is fine. As states and actions grow, every method repeats the same switch, the rules for one situation are spread across many methods, and a new state means editing all of them. State classes group the rules by situation instead.

What is the difference between State and Strategy?

They share a structure but differ in intent. A strategy is chosen by the client and usually stays fixed, and strategies are independent. States are switched by the object itself as events happen, and a state often knows which state comes next.

Who should decide the next state: the state classes or the context?

Either works. Letting each state choose keeps rules and transitions together but couples states to each other; letting the context or a transition table decide keeps the whole graph in one place. Choose one and explain the trade-off.

Can state objects be shared between contexts?

Yes, if they hold no fields. Keep the data in the context and each state can be a single shared instance, a static constant or an enum constant that implements the state interface. States with their own data, such as a retry count, need a new instance per transition.

How do you handle an action that is not valid in the current state?

Define it explicitly: throw an exception, return an error result or ignore it with a message, but never silently do the wrong thing. Default methods on the state interface that refuse the action keep the concrete states small.

Which LLD interview problems use the State pattern?

Vending machine (idle, has money, maintenance), elevator (idle, moving, doors open), ATM (no card, card inserted, authenticated), traffic signals, order lifecycles and document workflows. Drawing the transition table first is the strongest signal.

How do you make a State-based object thread-safe?

The current state and the context’s data change together, so guard each public method of the context with one lock, for example by making them synchronized. Stateless shared state objects need no locking of their own.