Browse Java Design Patterns & Enterprise Application Architecture

Implementing State in Java

Implement State in Java by moving state-specific behavior out of sprawling conditionals and into explicit state objects or state models.

On this page

State: A pattern that changes an object’s behavior by delegating state-specific logic to explicit state representations.

A Java state design usually has:

  • a context that owns the current state
  • state objects or state-specific handlers
  • transitions that change which state handles behavior
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}

Why It Helps

The pattern localizes state-specific rules instead of scattering them across:

  • switch statements
  • status flags
  • duplicated guard logic

When To Avoid It

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.

Revised on Thursday, April 23, 2026