Behavioral Design Pattern
State Design Pattern in Java
Allow an object to change its behavior when its internal state changes.
In this lesson: State moves state-specific behavior into separate objects. The context delegates work to the current state instead of growing a large conditional statement.
Overview
State is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.
Implementation
interface OrderState { void next(Order order); }
final class Order { private OrderState state; Order(OrderState state) { this.state = state; } void next() { state.next(this); } void state(OrderState state) { this.state = state; } }
final class NewOrder implements OrderState { public void next(Order order) { order.state(new ShippedOrder()); } }
final class ShippedOrder implements OrderState { public void next(Order order) { System.out.println("Delivered"); } }
When should you use it?
Use State for order workflows, connection lifecycles, media players, and other objects whose behavior changes across well-defined states.
Next step: Continue with the Design Patterns course and explore the next pattern.