Knowledge Guide
HomeOO & Low-Level DesignBehavioral

State Pattern

The State design pattern enables an object's behavior to change when its internal state changes. This pattern is used to encapsulate varying behavior for the same routine based on the object's state, allowing an object to change its behavior at runtime without resorting to large conditional statements.

Consider the music player app. The music player can be in any of the following states: stopped, paused, or playing. Depending on the player's current condition, different behaviors are displayed by the buttons labeled "play," "pause," "stop," and "next." It can be difficult and challenging to maintain this implementation when there are a lot of conditional statements, especially when more states or actions are added.

Solution: The State pattern recommends developing distinct classes that implement the same interface or abstract class for each state of the music player, such as PlayingState, PausedState, and StoppedState. The behavior is delegated to the current state object by the MusicPlayer class, which keeps track of it. The Music Player modifies the state object it refers to when the state changes.

State Pattern - Music Player
State Pattern - Music Player

Real-World Example

Consider a system of traffic lights. There are three possible states for the traffic light: red, green, or yellow. Each state requires a distinct set of actions:

State Pattern - Real Life Example
State Pattern - Real Life Example

The traffic light's behavior varies in accordance with the precise sequence in which it changes states—from Red to Green to Yellow to Red.

Structure of State Pattern

The key components of the class diagram include:

State Pattern - Class Diagram
State Pattern - Class Diagram

The class diagram shows the Context class having a reference to the State interface and the Concrete State classes implementing the State interface. The interaction between the Context and the Concrete States encapsulates the state-dependent behavior.

Implementation of State Interface

Let's take the example of a Document class that can be in different states: Draft, Moderation, and Published.

// State Interface interface State { void publish(document) void approve(document) } // Concrete States class Draft implements State { void publish(document) { document.state = new Moderation() } void approve(document) { // Draft cannot be approved directly } } class Moderation implements State { void publish(document) { // Cannot publish from Moderation without approval } void approve(document) { document.state = new Published() } } class Published implements State { void publish(document) { // Already published } void approve(document) { // Already approved } } // Context Class class Document { State state = new Draft() void publish() { state.publish(this) } void approve() { state.approve(this) } } // Usage document = new Document() document.publish() // Changes state to Moderation document.approve() // Changes state to Published

Implementation

java
interface State {
  void publish(Document doc);
  void approve(Document doc);
}

class Document {

  private State state;

  public Document() {
    this.state = new Draft();
  }

  public void setState(State state) {
    this.state = state;
  }

  public void publish() {
    state.publish(this);
  }

  public void approve() {
    state.approve(this);
  }
}

class Draft implements State {

  public void publish(Document doc) {
    System.out.println("Publishing draft, moving to moderation.");
    doc.setState(new Moderation());
  }

  public void approve(Document doc) {
    System.out.println("Draft cannot be approved directly.");
  }
}

class Moderation implements State {

  public void publish(Document doc) {
    System.out.println("Cannot publish from Moderation without approval.");
  }

  public void approve(Document doc) {
    System.out.println("Approving moderation, moving to published.");
    doc.setState(new Published());
  }
}

class Published implements State {

  public void publish(Document doc) {
    System.out.println("Already published.");
  }

  public void approve(Document doc) {
    System.out.println("Already approved.");
  }
}

public class Solution {

  public static void main(String[] args) {
    Document doc = new Document();
    doc.publish();
    doc.approve();
  }
}

Applications of State Pattern

In each of these applications, the State pattern contributes to a cleaner, more organized, and maintainable codebase by encapsulating state-specific behaviors and facilitating state transitions in a controlled manner.

Pros and Cons

ProsCons
Encapsulates State-Specific Behavior: Each state's behavior is in its class.Increased Number of Classes: More classes to manage for each state.
Easier Maintenance: Adding new states or changing behaviors doesn't require modifying existing states.Context-Dependency: States are dependent on the context, making them less reusable.
Eliminates Complex Conditional Logic: Avoids conditional complexity in the context class.Complexity: Initial setup and understanding of the pattern can be complex.
Improves Readability: Clear structure for state transitions.Overhead: Additional overhead in terms of memory and runtime for small use cases.

The State design pattern is an effective tool for managing state-dependent behavior in a clean and maintainable manner. It's especially helpful when an object's behavior varies greatly depending on its state. Understanding this pattern can significantly reduce the complexity of code structure in complex systems.

🤖 Don't fully get this? Learn it with Claude

Stuck on State Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **State Pattern** (OO & Low-Level Design) and want to truly understand it. Explain State Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **State Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **State Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **State Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes