Behavioral PatternINTERMEDIATE8 min deep dive

State Pattern Pattern

Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

Real-World Mental Model / Metaphor:

A smartphone. Pressing the power button behaves differently depending on current state: if phone is Locked -> Screen wakes up. If phone is Unlocked -> Screen turns off. If phone is Ringing -> Silences ringer.

Interactive Runtime Simulator

Test and tweak inputs dynamically

Interactive State Pattern SimulatorLIVE PLAYGROUND

Interact with the controls below to see how this design pattern executes in memory at runtime.

Category: Behavioral
Current Document State:DRAFT
State Rules Enforced:
  • Draft cannot publish directly (must pass Moderation).
  • Published document content is immutable.
  • State transitions are managed by State classes, not large switches.
STATE TRANSITION AUDIT LOG
> Document created in DRAFT state.
State Machine Flow:
[DRAFT][MODERATION][PUBLISHED]
The Problem It Solves

Gigantic methods filled with conditional operators (`if (state == DRAFT) ... else if (state == REVIEW) ...`) that become nightmare bugs when a new state is added.

The Architectural Solution

Create separate state classes for each possible state that implement a common State interface. The Context object delegates actions to the current State object.

Pattern Structure & Participants

ParticipantRole & ResponsibilityType
State (Interface)Declares actions like publish(), edit()interface
Draft, Review, PublishedConcrete states handling actions and transitioning contextclass
Document (Context)Maintains reference to current stateclass
Collaboration Rules:
  • Context delegates document.publish() to currentState.publish(document)
  • State transitions context: document.setState(new PublishedState())

Production Code Implementation

State Pattern.java
public interface DocumentState {
    void edit(Document doc, String text);
    void submitForReview(Document doc);
    void publish(Document doc);
    String getStatus();
}

public class DraftState implements DocumentState {
    public void edit(Document doc, String text) {
        doc.setContent(text);
        System.out.println("Draft updated.");
    }
    public void submitForReview(Document doc) {
        doc.setState(new ModerationState());
        System.out.println("Document moved to Moderation.");
    }
    public void publish(Document doc) {
        System.out.println("Error: Cannot publish a draft directly without review!");
    }
    public String getStatus() { return "DRAFT"; }
}

public class PublishedState implements DocumentState {
    public void edit(Document doc, String text) {
        System.out.println("Error: Cannot edit an immutable published document!");
    }
    public void submitForReview(Document doc) {
        System.out.println("Already approved and published.");
    }
    public void publish(Document doc) {
        System.out.println("Already published live.");
    }
    public String getStatus() { return "PUBLISHED"; }
}

public class Document {
    private DocumentState state = new DraftState();
    private String content = "";

    public void setState(DocumentState state) { this.state = state; }
    public void setContent(String content) { this.content = content; }
    
    public void edit(String text) { state.edit(this, text); }
    public void submit() { state.submitForReview(this); }
    public void publish() { state.publish(this); }
    public String getStatus() { return state.getStatus(); }
}
When to Use:
  • •When you have an object that behaves differently depending on its current state, the number of states is enormous, and state-specific code changes frequently.
  • •When you have a class polluted with massive conditionals that duplicate state transitions across methods.
When to Avoid (Anti-Pattern):
  • •When a state machine is trivial (e.g. only 2 states like on/off) and unlikely to change.

Staff Engineering Interview Insights & Gotchas

  • Compare State Pattern vs Strategy Pattern: they have identical UML class diagrams, but Strategy represents interchangeable algorithms, while State represents internal state transitions where states often know about each other.
  • Discuss how State Pattern models real-world e-commerce inventory and order fulfillments.