GoF pattern • Behavioral
GoFBehavioralJava example
State solves a specific structural problem in the design.
Change behavior by switching state objects instead of conditionals.
Pattern overview
GoF pattern
Change behavior by switching state objects instead of conditionals.
Intent
Allow an object to alter its behavior when its internal state changes.
Problem
Behavior varies by lifecycle phase, and condition-heavy code becomes hard to extend or reason about.
Solution
Represent each state as an object that knows the allowed behavior and transitions.
Fit and tradeoffs
FamilyGoF
CategoryBehavioral
Best used when
- For workflows, lifecycle-heavy entities, and status-driven logic.
Tradeoffs
- Adds more types than a simple enum-based conditional.
- Best when state-specific behavior is meaningful, not trivial.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
interface DocumentState {
void publish(DocumentContext context);
}
final class DraftState implements DocumentState {
public void publish(DocumentContext context) {
context.setState(new PublishedState());
}
}
final class PublishedState implements DocumentState {
public void publish(DocumentContext context) {
throw new IllegalStateException("Document already published");
}
}