Behavioral PatternsState PatternEasy⏱️ ~2 min

What is the State Pattern?

Definition
State Pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

The State Pattern encapsulates state-specific behavior inside separate state classes and delegates behavior to the current state object. When the state changes, the context switches to a different state object, which changes the behavior automatically.

Problem It Solves

Without the State Pattern, you end up with large conditional statements (if-else or switch-case) scattered throughout your code to handle different behaviors based on state. This violates the Open/Closed Principle (OCP) because adding a new state requires modifying existing code.

Without State Pattern:
if (state == DRAFT) {
  // Draft behavior
} else if (state == MODERATION) {
  // Moderation behavior
} else if (state == PUBLISHED) {
  // Published behavior
}

Core Benefits

First, it eliminates complex conditional logic by distributing state-specific behavior across separate classes. Second, it makes state transitions explicit and centralized. Third, adding new states becomes easy without modifying existing state classes or the context (OCP compliance).

Interview Tip: Always emphasize that State Pattern is about behavior change, not just data change. A simple status flag is not the State Pattern unless it triggers different method implementations.
💡 Key Takeaways
Encapsulates state-specific behavior in separate state classes
Context delegates work to current state object
State transitions become explicit instead of hidden in conditionals
Follows Open/Closed Principle by allowing new states without modifying existing code
Different from Strategy Pattern because states can trigger transitions
📌 Examples
1Document workflow (draft, moderation, published)
2Vending machine (idle, has money, dispensing)
3TCP connection (listening, established, closed)
4Order processing (pending, confirmed, shipped, delivered)
← Back to State Pattern Overview
What is the State Pattern? | State Pattern - System Overflow