These are the notes for Low-Level Design (LLD) episode 37, the fourth behavioural pattern (patterns about how objects share work and talk to each other). The State pattern lets an object change its behaviour when its state changes, without a giant if-else on a status field. We start with a phone's power button, watch Asha's delivery app refund an order that was already delivered, draw the order as a finite state machine, and invent the pattern as the fix. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.
1. The real-life idea: one button, three behaviours
| Your phone | In code |
|---|---|
| The phone: one object, one power button | The context: the object whose behaviour changes |
| Off, locked, unlocked | The state: the condition the object is in right now |
| Pressing the button | An event: an input that may change the state |
| Off: a press turns it on. Unlocked: the same press locks it | Behaviour per state: each state decides what an event does |
The button never asks "am I off? am I locked?". Each state simply knows what a press means. That is the whole idea of the State pattern.
2. The problem: a delivered order, refunded
An Order keeps its status as a plain String and every method is an if-else chain on it.
class Order {
String status = "PLACED";
void next() {
if (status.equals("PLACED")) status = "PREPARING";
else if (status.equals("PREPARING")) status = "OUT_FOR_DELIVERY";
else if (status.equals("OUT_FOR_DELIVERY")) status = "DELIVERED";
else System.out.println("no next step from " + status);
}
void cancel() {
if (status.equals("OUT_FOR_DELIVERY")) System.out.println("too late: rider is on the way");
else { status = "CANCELLED"; System.out.println("cancelled, refund Rs 250"); }
}
}
public class Main {
public static void main(String[] args) {
Order o = new Order();
o.next(); o.next(); o.next();
System.out.println("status: " + o.status);
o.cancel(); // a delivered dosa, cancelled?
System.out.println("status: " + o.status);
}
}
status: DELIVERED
cancelled, refund Rs 250
status: CANCELLED
No error, just the wrong behaviour: an order that was already delivered was cancelled and refunded Rs 250. Whoever wrote cancel() forgot the DELIVERED case.
Why it failed
- Every method repeats the same status checks (
next(),cancel(), and any futuretrack()orrefund()). - Miss one case in one method and you get wrong behaviour with no error.
- A new state (say
READY_FOR_PICKUP) means finding and editing every chain. - A
Stringstatus lets a typo like"PLACD"compile happily. - Like the phone: let each state decide, and keep all of one state's rules in one place.
3. Drawing it first: the finite state machine
next next next
●──► [Placed] ───► [Preparing] ───► [Out for delivery] ───► [Delivered]
│ │
cancel │ │ cancel
▼ ▼
[Cancelled]
- A state is a situation the object can be in (a rounded box).
- An event is something that happens (
next,cancel), written on an arrow. - A transition is a move from one state to another, caused by an event (an arrow).
- The black dot is the start: every order begins in
Placed. - An event with no arrow out of the current state is an invalid transition:
cancelfromOut for deliveryorDelivered,nextfromDeliveredorCancelled. It must be rejected. - A finite state machine (FSM) is a fixed, countable set of states plus the events that move between them. Tickets, payments, traffic signals and lifts are all state machines.
The buggy code had this machine in it, but scattered across if-else chains, so one arrow was drawn wrong.
4. The fix: one class per state
interface OrderState { // the state interface
default OrderState next() { System.out.println(" no next step"); return this; }
default OrderState cancel() { System.out.println(" can't cancel now"); return this; }
}
class Placed implements OrderState { // concrete states
public OrderState next() { return new Preparing(); }
public OrderState cancel() { System.out.println(" cancelled, refund Rs 250"); return new Cancelled(); }
}
class Preparing implements OrderState {
public OrderState next() { return new OutForDelivery(); }
public OrderState cancel() { System.out.println(" cancelled, refund Rs 200"); return new Cancelled(); }
}
class OutForDelivery implements OrderState { public OrderState next() { return new Delivered(); } }
class Delivered implements OrderState { } // keeps the defaults: rejects both
class Cancelled implements OrderState { }
class Order { // the context
private OrderState state = new Placed();
void next() { state = state.next(); }
void cancel() { state = state.cancel(); }
String status() { return state.getClass().getSimpleName(); }
}
public class Main {
public static void main(String[] args) {
Order a = new Order(); a.next(); a.next(); a.next(); a.cancel();
Order b = new Order(); b.next(); b.cancel(); b.next();
System.out.println("A: " + a.status() + ", B: " + b.status());
}
}
can't cancel now
cancelled, refund Rs 200
no next step
A: Delivered, B: Cancelled
How it works:
OrderStateis the state interface: one method per event. Each method returns the state the order should be in afterwards. The default methods (episode 3) reject the event and returnthis, meaning "stay where you are".Placed,Preparing,OutForDelivery,DeliveredandCancelledare concrete states. Each one overrides only the events it allows.DeliveredandCancelledare empty: they reject everything. Each arrow in the diagram is one line of code.Orderis the context. It holds the current state and does no checking at all:next()asks the state and stores whatever comes back. Handing the work to another object like this is called delegation.- There is not a single
ifon the status anywhere.
5. It has a name: the State pattern
+---------------------+ current state +-----------------------------+
| Order «context» |------------------>| «interface» OrderState |
| - state: OrderState | | + next(): OrderState |
| + next() + cancel()| | + cancel(): OrderState |
+---------------------+ +-----------------------------+
^ ^ ^ ^ ^ (implements)
Placed Preparing OutForDelivery Delivered Cancelled «concrete states»
The classic intent (SourceMaking): "Allow an object to alter its behavior when its internal state changes. The object will appear to change its class." It is also described as "An object-oriented state machine". The same cancel() call on the same Order object behaved like a different class once the order was delivered.
| Role | In our example | Job |
|---|---|---|
| Context | Order |
What the outside world talks to; holds the current state; delegates every event |
| State interface | OrderState |
One method per event |
| Concrete state | Placed, Preparing, ... |
The rules for one state; returns the next state |
Open-closed (episode 13): adding ReadyForPickup is one new class plus a change to the one state that leads to it. No other state is touched. See the mini project.
Who decides the transition? Here each state returns the next state (the states know their successors). The alternative is that the context decides, using a table (section 7). Both are valid; states-decide keeps each state's rules together.
6. The trap: an open state field
If the state field is not private, outside code can walk around the rules:
interface OrderState { // the state interface
default OrderState next() { System.out.println(" no next step"); return this; }
default OrderState cancel() { System.out.println(" can't cancel now"); return this; }
}
class Placed implements OrderState { // concrete states
public OrderState next() { return new Preparing(); }
public OrderState cancel() { System.out.println(" cancelled, refund Rs 250"); return new Cancelled(); }
}
class Preparing implements OrderState {
public OrderState next() { return new OutForDelivery(); }
public OrderState cancel() { System.out.println(" cancelled, refund Rs 200"); return new Cancelled(); }
}
class OutForDelivery implements OrderState { public OrderState next() { return new Delivered(); } }
class Delivered implements OrderState { } // keeps the defaults: rejects both
class Cancelled implements OrderState { }
class Order { // the context
OrderState state = new Placed(); // not private!
void next() { state = state.next(); }
void cancel() { state = state.cancel(); }
String status() { return state.getClass().getSimpleName(); }
}
public class Main {
public static void main(String[] args) {
Order b = new Order(); // just placed...
b.state = new Delivered(); // ...skips cooking and the rider
System.out.println("B: " + b.status());
}
}
B: Delivered
Order B was only placed, yet it is now Delivered: it skipped cooking and the rider. Make the field private, and the compiler guards the machine:
interface OrderState { // the state interface
default OrderState next() { System.out.println(" no next step"); return this; }
default OrderState cancel() { System.out.println(" can't cancel now"); return this; }
}
class Placed implements OrderState { // concrete states
public OrderState next() { return new Preparing(); }
public OrderState cancel() { System.out.println(" cancelled, refund Rs 250"); return new Cancelled(); }
}
class Preparing implements OrderState {
public OrderState next() { return new OutForDelivery(); }
public OrderState cancel() { System.out.println(" cancelled, refund Rs 200"); return new Cancelled(); }
}
class OutForDelivery implements OrderState { public OrderState next() { return new Delivered(); } }
class Delivered implements OrderState { } // keeps the defaults: rejects both
class Cancelled implements OrderState { }
class Order { // the context
private OrderState state = new Placed(); // only states move it
void next() { state = state.next(); }
void cancel() { state = state.cancel(); }
String status() { return state.getClass().getSimpleName(); }
}
public class Main {
public static void main(String[] args) {
Order b = new Order(); // just placed...
b.state = new Delivered(); // ...skips cooking and the rider
System.out.println("B: " + b.status());
}
}
Main.java:25: error: state has private access in Order
b.state = new Delivered(); // ...skips cooking and the rider
^
1 error
Remove that line; the only way to move an order is through its events, next() and cancel().
7. An enum transition table
For a simple machine, an enum (episode 3) lists the states, so typos don't compile, and a transition table stores the arrows as data: a map from each state to the set of states it may move to.
EnumMap<K, V>: aMapwhose keys are the constants of one enum; fast and ordered by the enum.EnumSet: aSetof constants of one enum.EnumSet.of(...),EnumSet.noneOf(Status.class)(empty).
import java.util.*;
enum Status { PLACED, PREPARING, OUT_FOR_DELIVERY, DELIVERED, CANCELLED }
class Order {
private static final Map<Status, Set<Status>> ALLOWED = new EnumMap<>(Status.class);
static { // the transition table
ALLOWED.put(Status.PLACED, EnumSet.of(Status.PREPARING, Status.CANCELLED));
ALLOWED.put(Status.PREPARING, EnumSet.of(Status.OUT_FOR_DELIVERY, Status.CANCELLED));
ALLOWED.put(Status.OUT_FOR_DELIVERY, EnumSet.of(Status.DELIVERED));
ALLOWED.put(Status.DELIVERED, EnumSet.noneOf(Status.class));
ALLOWED.put(Status.CANCELLED, EnumSet.noneOf(Status.class));
}
private Status status = Status.PLACED;
void moveTo(Status to) {
if (!ALLOWED.get(status).contains(to))
throw new IllegalStateException("Illegal transition: " + status + " -> " + to);
System.out.println(status + " -> " + to); status = to;
}
}
public class Main {
public static void main(String[] args) {
Order o = new Order();
o.moveTo(Status.PREPARING);
o.moveTo(Status.OUT_FOR_DELIVERY);
o.moveTo(Status.DELIVERED);
o.moveTo(Status.CANCELLED); // a delivered order, cancelled?
}
}
PLACED -> PREPARING
PREPARING -> OUT_FOR_DELIVERY
OUT_FOR_DELIVERY -> DELIVERED
Exception in thread "main" java.lang.IllegalStateException: Illegal transition: DELIVERED -> CANCELLED
at Order.moveTo(Main.java:16)
at Main.main(Main.java:26)
moveTo fails fast: an invalid transition throws IllegalStateException at the exact line, instead of quietly refunding a dosa. IllegalStateException is Java's standard unchecked exception for "this call is not allowed in the object's current state".
Table or classes? Use a table when states differ only in where they can go. When each state also behaves differently (different refunds, messages, fees), the State pattern's classes keep that behaviour in one place.
8. Enum-based state machines
An enum constant can have its own body, so each constant can be a state with its own behaviour:
enum Signal { // each constant is a state
RED(30) { Signal next() { return GREEN; } },
GREEN(25) { Signal next() { return YELLOW; } },
YELLOW(5) { Signal next() { return RED; } };
final int seconds;
Signal(int seconds) { this.seconds = seconds; }
abstract Signal next(); // every state must say what comes next
}
public class Main {
public static void main(String[] args) {
Signal s = Signal.RED;
for (int i = 0; i < 4; i++) {
System.out.println(s + " for " + s.seconds + " s");
s = s.next();
}
}
}
RED for 30 s
GREEN for 25 s
YELLOW for 5 s
RED for 30 s
abstract Signal next();forces every constant to definenext(). Add aFLASHINGcolour and forget it, and the code won't compile.- Each state carries data (
seconds). - Every constant is one shared object. That's safe only because these states hold no data that belongs to one signal. If a state needs per-object data (like the order amount), keep that data in the context and pass the context in (see the mini project).
9. State vs Strategy (and when to use State)
| Strategy (episode 34) | State | |
|---|---|---|
| Shape in code | Context holds an interface object | Context holds an interface object |
| Who picks the object? | The client, from outside ("pay by UPI") | The states themselves, as events arrive |
| How often it changes | Rarely; usually fixed per use | Constantly, as part of normal work |
| Do the objects know each other? | No | Yes: a state knows which state comes next |
Use State when behaviour depends on a status with rules for moving between values: orders, payments, tickets, bookings, lifts, document approval. Use an enum table when states only differ in where they can go. For two states, a boolean and one if may be simpler.
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
if-else on a String status in every method |
No error: cancelled, refund Rs 250 for a delivered order |
One case forgotten in one method | One class per state |
| Non-private state field | No error: B: Delivered (skipped two states) |
Outside code bypasses the rules | private; move only via events. Compiler: error: state has private access in Order |
| Silently ignoring an invalid move | Bugs hide until a customer complains | Invalid transition swallowed | Reject clearly, or fail fast: java.lang.IllegalStateException: Illegal transition: DELIVERED -> CANCELLED |
| Shared state object holding per-order data | No error: one order's data leaks into another | One instance used by many contexts | Keep data in the context; pass it in |
| Typos in status strings | No error: "PLACD" never matches |
Strings aren't checked by the compiler | Enum or state classes |
Mini project: add a ReadyForPickup state
Pickup orders go Placed → Preparing → ReadyForPickup → Delivered; delivery orders go through OutForDelivery. The refund amount comes from the order (the context), so the state objects stay free of per-order data.
interface OrderState {
default OrderState next(Order o) { System.out.println(" no next step"); return this; }
default OrderState cancel(Order o) { System.out.println(" can't cancel now"); return this; }
}
class Placed implements OrderState {
public OrderState next(Order o) { return new Preparing(); }
public OrderState cancel(Order o) { System.out.println(" refund Rs " + o.amount); return new Cancelled(); }
}
class Preparing implements OrderState {
public OrderState next(Order o) { return o.pickup ? new ReadyForPickup() : new OutForDelivery(); } // NEW branch
}
class ReadyForPickup implements OrderState { // NEW state: one class
public OrderState next(Order o) { return new Delivered(); }
}
class OutForDelivery implements OrderState { public OrderState next(Order o) { return new Delivered(); } }
class Delivered implements OrderState { }
class Cancelled implements OrderState { }
class Order {
final int amount; final boolean pickup;
private OrderState state = new Placed();
Order(int amount, boolean pickup) { this.amount = amount; this.pickup = pickup; }
void next() { state = state.next(this); System.out.println(" -> " + status()); }
void cancel() { state = state.cancel(this); }
String status() { return state.getClass().getSimpleName(); }
}
public class Main {
public static void main(String[] args) {
System.out.println("pickup order:"); Order p = new Order(180, true); p.next(); p.next(); p.next();
System.out.println("delivery order:"); Order d = new Order(250, false); d.next(); d.next(); d.cancel();
}
}
pickup order:
-> Preparing
-> ReadyForPickup
-> Delivered
delivery order:
-> Preparing
-> OutForDelivery
can't cancel now
Only Preparing changed, and ReadyForPickup was added. Every other state is untouched.
Practice
1. Model a lift with IDLE, MOVING_UP, MOVING_DOWN and DOORS_OPEN as enum constants with bodies. Call it from floor 0 to floor 3.
Answer
enum Lift {
IDLE { Lift call(int from, int to) { return from == to ? DOORS_OPEN : (to > from ? MOVING_UP : MOVING_DOWN); } },
MOVING_UP { Lift call(int from, int to) { return from == to ? DOORS_OPEN : this; } },
MOVING_DOWN { Lift call(int from, int to) { return from == to ? DOORS_OPEN : this; } },
DOORS_OPEN { Lift call(int from, int to) { return from == to ? this : (to > from ? MOVING_UP : MOVING_DOWN); } };
abstract Lift call(int from, int to);
}
public class Main {
public static void main(String[] args) {
Lift s = Lift.IDLE; int floor = 0, target = 3;
s = s.call(floor, target); System.out.println("floor " + floor + ": " + s);
while (s != Lift.DOORS_OPEN) {
floor += (s == Lift.MOVING_UP) ? 1 : -1;
s = s.call(floor, target);
System.out.println("floor " + floor + ": " + s);
}
}
}
floor 0: MOVING_UP
floor 1: MOVING_UP
floor 2: MOVING_UP
floor 3: DOORS_OPEN
Each constant decides the next state from the current floor and the target. The doors open when from == to.
2. Change the transition table so an invalid move is logged and rejected instead of throwing.
Answer
import java.util.*;
enum Status { PLACED, PREPARING, OUT_FOR_DELIVERY, DELIVERED, CANCELLED }
class Order {
private static final Map<Status, Set<Status>> ALLOWED = new EnumMap<>(Status.class);
static {
ALLOWED.put(Status.PLACED, EnumSet.of(Status.PREPARING, Status.CANCELLED));
ALLOWED.put(Status.PREPARING, EnumSet.of(Status.OUT_FOR_DELIVERY, Status.CANCELLED));
ALLOWED.put(Status.OUT_FOR_DELIVERY, EnumSet.of(Status.DELIVERED));
ALLOWED.put(Status.DELIVERED, EnumSet.noneOf(Status.class));
ALLOWED.put(Status.CANCELLED, EnumSet.noneOf(Status.class));
}
private Status status = Status.PLACED;
private final List<String> log = new ArrayList<>();
boolean tryMoveTo(Status to) { // returns false instead of throwing
if (!ALLOWED.get(status).contains(to)) { log.add("REJECTED " + status + " -> " + to); return false; }
log.add(status + " -> " + to); status = to; return true;
}
List<String> log() { return log; }
}
public class Main {
public static void main(String[] args) {
Order o = new Order();
o.tryMoveTo(Status.PREPARING); o.tryMoveTo(Status.DELIVERED);
o.tryMoveTo(Status.CANCELLED); o.tryMoveTo(Status.PREPARING);
o.log().forEach(System.out::println);
}
}
PLACED -> PREPARING
REJECTED PREPARING -> DELIVERED
PREPARING -> CANCELLED
REJECTED CANCELLED -> PREPARING
Whether to throw or to return false is a design decision: throw when a bad move means a bug in your code; return a result when bad moves are expected input (a user pressing the wrong button).
3. In the State-pattern version, what must you change to allow cancelling an order that is out for delivery, with a Rs 50 fee?
Answer
Only OutForDelivery: add public OrderState cancel() { System.out.println(" cancelled, fee Rs 50"); return new Cancelled(); }. No other class changes, which is exactly the point of the pattern.
Quick quiz
Order o = new Order(); // Placed
o.next();
o.next();
o.cancel();
System.out.println(o.status());
(a) Cancelled (b) OutForDelivery (c) Preparing (d) Delivered
Answer
(b) OutForDelivery. Two next() calls: Placed → Preparing → OutForDelivery. OutForDelivery keeps the default cancel(), which prints can't cancel now and returns this.
Interview questions
- What is the State pattern? A behavioural pattern where an object delegates its behaviour to a state object, and swaps that object as its state changes, so it appears to change its class.
- Participants? Context, state interface, concrete states.
- Who performs the transitions? Either the concrete states (each returns or sets the next state) or the context (often with a transition table). States-decide keeps rules together; context-decide keeps states independent of each other.
- What is a finite state machine? A fixed set of states, events, and transitions between states caused by events, with a start state.
- How do you handle invalid transitions? Reject them explicitly: throw
IllegalStateException(fail fast) or return a result the caller must check. Never ignore them silently. - State vs Strategy? Same structure; strategies are chosen by the client and rarely change, states change themselves as events arrive and know their successors.
- Can states be singletons? Yes, if they hold no per-context data (enum constants are a natural fit). Keep per-object data in the context.
- How does State relate to the open-closed principle? A new state is a new class; existing states and the context don't change.
- When is State overkill? Two states, or states that differ only in allowed moves (use an enum table).
- Real examples? Order and payment lifecycles, TCP connection states, media players (playing, paused, stopped), vending machines, document workflows, game character modes.
Glossary
| Term | Meaning, with an example |
|---|---|
| Behavioural pattern | A pattern about how objects share work and communicate |
| State pattern | Let an object change its behaviour when its state changes, by delegating to a state object. Order + OrderState |
| State | The condition an object is in right now. An order is Preparing |
| Event | Something that happens to an object and may change its state. next(), cancel(), a button press |
| Transition | A move from one state to another, caused by an event. Placed --next--> Preparing |
| State transition | Same as transition |
| Invalid transition | An event that has no arrow out of the current state. cancel on a delivered order |
| Finite state machine (FSM) | A fixed, countable set of states, a start state, and transitions between them. A traffic signal |
| State diagram | A drawing of an FSM: boxes for states, arrows labelled with events |
| Context | The object the rest of the program talks to; holds the current state and delegates to it. Order |
| State interface | One method per event, implemented by every state. OrderState |
| Concrete state | One class with the rules for one state. Placed, Delivered |
| Delegation | Handing work to another object. state = state.next() |
| Default method | An interface method with a body (episode 3); here, "reject" for every event |
private |
Visible only inside its own class; keeps outside code from changing the state directly |
| Enum | A type with a fixed set of named constants. enum Status { PLACED, ... } |
| Enum constant with a body | A constant that overrides methods: RED { Signal next() { return GREEN; } } |
| Enum-based state machine | States as enum constants, each defining its own transitions |
| Transition table | Data that lists, for each state, the states it may move to. EnumMap<Status, Set<Status>> |
EnumMap |
A Map whose keys are enum constants |
EnumSet |
A Set of enum constants. EnumSet.of(A, B), EnumSet.noneOf(Status.class) |
IllegalStateException |
Java's unchecked exception for "not allowed in the current state" |
| Fail fast | Stop with a clear error at the first sign of a bug, instead of continuing with wrong data |
| Order lifecycle | The states an order passes through from placed to delivered or cancelled |
| Strategy | One algorithm per class, chosen from outside (episode 34) |
| State vs Strategy | Same shape; strategies are picked by the client, states pick the next state themselves |
| Open-closed principle | Open for extension, closed for modification (episode 13) |
Summary
- An
if-elseon a status string in every method breaks quietly: one missed case refunded a delivered order. - Draw the finite state machine first: states, events, transitions; missing arrows are invalid transitions.
- State pattern: the context delegates every event to its current state object; each concrete state returns the next state.
- Keep the state field private; reject invalid transitions clearly or fail fast.
- For simple machines: an enum +
EnumMaptransition table, or enum constants with bodies. - State vs Strategy: same shape; states change themselves, strategies are chosen from outside.
Next episode: The Template Method pattern: write an algorithm's steps once, and let subclasses fill in the details.