State pattern
The state pattern encapsulates state-specific behavior into separate objects, eliminating large switch statements and making each state's logic independently testable.
Introduction
The State pattern represents behavior that changes with an object's current lifecycle state. A context delegates an operation to its current state object, and each concrete state owns the actions and transitions that are valid from that point in the lifecycle.
TL;DR / mental model
Replace a status field plus repeated switches with a current-state object. The context stays small, each state handles its own rules, and transitions move the context to the next state when the domain allows them.
Problem and Context
You're building an order management system. An order moves through Pending, Confirmed, Shipped, Delivered, and Cancelled. Without a pattern, every method on the order becomes a switch statement that checks which state it's in.
Five states, five methods = 25 switch branches today. If a "ReturnRequested" state is added next sprint, every method may need another branch. Finding all the rules for the "Shipped" state means scanning the entire class; as these switches grow, incident diagnosis and maintenance become harder.
Here is what changes when you apply the State pattern.
State Transition Diagram
Before diving into code, visualize the valid transitions. This diagram becomes the source of truth for which state can move where.
Notice that not every state can reach every other state. Shipped orders cannot be cancelled. Pending orders cannot be delivered directly. The state pattern makes these rules explicit by placing the transition logic inside each state class.
Participants and Structure
Order is the context: it holds a reference to currentState and delegates every action to it. Each concrete state class implements only the transitions that are valid from that state. Invalid actions throw or log a meaningful message. The key insight: states know about each other (PendingState references ConfirmedState), which is the structural difference from Strategy.
Idiomatic Example and Implementation Notes
Continue Reading with Premium
Unlock this article and every other in-depth system design guide on the platform with SDEpedia Premium.
Related Articles
The strategy pattern extracts a family of algorithms behind an interface so the client can swap behaviors at runtime without touching the context class.
The memento pattern captures an object's internal state as an opaque snapshot and restores it later, enabling undo and rollback without breaking encapsulation.
Learn the five SOLID principles by building a real order-processing system in Java, with before and after code for every principle.