State Pattern
Allow an object to alter its behaviour when its internal state changes — object appears to change class.
📌 Key IdeaEncapsulate each state as a class implementing shared `State` interface. Context holds current state reference and delegates operations — transitions swap state objects. Replaces giant switch(state) methods.
Visual
🎬 Context delegates to State object
TCPConnection.context.handle()
│
├─ EstablishedState ── send()
└─ ClosedState ── error()State transitions are explicit — each state class knows legal next moves.
When to Use
- Many modes with different behaviour (connection lifecycle, order workflow).
- Large conditional chains on an enum / phase field.
- States have entry/exit actions — classes clarify behaviour.
When NOT to Use
- Two states total with trivial branches — YAGNI.
Anti-Pattern (What NOT to Do)
switch on phase in every methodBadjavavoid ship(Order o) {
switch (o.phase) {
case NEW -> pay(o);
case PAID -> warehouse.pack(o);
default -> throw new IllegalStateException();
}
}
// same switch repeated in cancel(), refund(), ...Transitions and guards scattered; easy to miss a case.
The Right Way
State object owns behaviourGoodjava
interface OrderState { void pay(Order o); void ship(Order o); }
class PaidState implements OrderState {
public void ship(Order o) {
o.setState(new ShippedState());
warehouse.dispatch(o);
}
}Order delegates ship() to currentState; illegal ops become impossible or no-op.Pros & Cons
👍 Pros
- Eliminates sprawling switch/if state machines.
- Each state file stays small and testable.
👎 Cons
- More classes — overhead for tiny machines.
- Must keep transition table coherent.
Common Confusions Cleared Up
State vs Strategy
Strategy swaps algorithms deliberately from outside — usually stable choice. State transitions follow internal rules — object feels like it morphs as lifecycle progresses.
Interview Q&A
Likely Follow-up Questions
- State pattern vs enum + methods in Java 21?
Quick Cheat Sheet
IntentBehaviour follows current state object.
vs StrategyLifecycle vs pluggable policy.
KillsGiant
switch(phase).