Implement State in Java by moving state-specific behavior out of sprawling conditionals and into explicit state objects or state models.
State: A pattern that changes an object’s behavior by delegating state-specific logic to explicit state representations.
A Java state design usually has:
1public interface OrderState {
2 void pay(OrderContext context);
3 void ship(OrderContext context);
4}
1public final class PendingState implements OrderState {
2 @Override
3 public void pay(OrderContext context) {
4 context.setState(new PaidState());
5 }
6
7 @Override
8 public void ship(OrderContext context) {
9 throw new IllegalStateException("Cannot ship before payment");
10 }
11}
The pattern localizes state-specific rules instead of scattering them across:
If the lifecycle is tiny and stable, a full state object model may be more ceremony than value. Not every enum plus switch needs to become State.