Introduction
Imagine you are building a music player application.
The music player can exist in different states:
Playing
Paused
Stopped
Now consider what happens when a user presses the Play button.
If the player is currently:
Stopped → Start playing music
Paused → Resume music
Playing → Do nothing
Similarly, when the user presses Pause:
Playing → Pause music
Paused → Do nothing
Stopped → Invalid operation
A beginner may implement this using multiple if-else conditions.
Initially, this looks simple.
But as the number of states grows, the code becomes difficult to manage.
This is where the State Design Pattern helps.
What is the State Pattern?
The State Pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes.
In simple words:
The State Pattern enables an object to behave differently depending on its current state.Instead of writing large conditional statements, each state gets its own class.
The object delegates behavior to its current state object.
Real World Analogy
Think about a traffic signal.
The traffic signal can be in one of three states:
Red
Yellow
Green
The behavior changes depending on the current state.
For example:
When the signal changes:
Red → Green
Green → Yellow
Yellow → Red
Each state has its own rules and behavior.
The traffic signal itself does not contain a giant list of conditions.
Instead, each state represents a different behavior.
Why Do We Need the State Pattern?
Consider a document editor.
A document may be in different states:
Draft
Review
Published
Without the State Pattern:
As states increase:
Draft
Review
Approved
Published
Archived
Deleted
The code becomes full of conditions.
Problems Without State Pattern
1. Large Conditional Statements
Multiple methods start containing:
if(...)
else if(...)
else if(...)
The code becomes difficult to read.
2. Violatesthe Open-Closedd Principle
Adding a new state requires modifying existing code.
3. State Logic Is Scattered
State-specific behavior spreads across multiple methods.
4. Difficult Maintenance
Changing state behavior becomes risky.
Solution: State Pattern
The State Pattern moves state-specific behavior into separate classes.
Instead of:
One class containing all state logic
We create:
DraftState
ReviewState
PublishedState
Each state handles its own behavior.
Key Components of the State Pattern
The State Pattern typically consists of:
1. State Interface
Defines behavior common to all states.
2. Concrete States
Implement state-specific behavior.
3. Context
Maintains the current state.
4. Client
Interacts with the context.
Structure of State Pattern
State
▲
│
-------------------------
│ │ │
DraftState ReviewState PublishedState
▲
│
Context
Example: Music Player
Let's build a simple music player.
Step 1: Create State Interface
Step 2: Create Concrete States
Playing State:
Paused State:
Stopped State:
Step 3: Create Context
Step 4: Client Code
Output
Starting Music
Music Paused
Resuming Music
How the State Pattern Works
Let's understand the flow.
Step 1
The context stores the current state.
currentState
Step 2
The client requests an operation.
Step 3
The context delegates the call.
Step 4
The current state determines the behavior.
Different states produce different results.
State Transitions
A major feature of the State Pattern is state transitions.
Example:
Stopped
↓
Playing
↓
Paused
↓
Playing
↓
Stopped
The object moves from one state to another during its lifetime.
Improved State Transition Example
Often, states can change the context's state themselves.
Example:
This allows automatic transitions.
For example:
Draft → Review
Review → Published
Published → Archived
without requiring the client to manage every transition.
State Pattern vs Strategy Pattern
This is one of the most common interview questions.
At first glance, both patterns look similar.
Both use:
Composition
Interface
Concrete Classes
However, their intent is different.
| State Pattern | Strategy Pattern |
|---|---|
| Changes behavior based on internal state | Changes behavior based onthe selected algorithm |
| State transitions occur automatically | Client chooses strategy |
| Represents object state | Represents algorithm choice |
| Focuses on the lifecycle | Focuses on behavior selection |
Example Difference
Strategy:
Payment Method
UPI
Card
PayPal
User chooses the algorithm.
State:
Order Status
Placed
Packed
Shipped
Delivered
The system changes state automatically.
State Pattern vs Conditional Statements
Without State Pattern:
if(state == ...)
Appears everywhere.
With State Pattern:
currentState->handle(); The behavior is delegated.
This makes the code cleaner and easier to maintain.
Advantages of the State Pattern
1. Eliminates Large Conditionals
No need for huge if-else chains.
2. Supports the Open-Closed Principle
New states can be added without modifying existing states.
3. Better Organization
State-specific behavior stays together.
4. Easier Maintenance
Changes affect only the relevant state class.
5. Cleaner Code
Business logic becomes more readable.
Disadvantages of the State Pattern
1. More Classes
Each state requires a separate class.
2. Increased Complexity
For very small state machines, the pattern may be excessive.
3. Transition Logic Can Become Complex
Applications with many states may require careful management.
Real World Applications
The State Pattern is widely used in:
Media players
Traffic signal systems
ATMs
Vending machines
Document workflows
Order management systems
Game character states
Network connection management
Workflow engines
Authentication systems
Many workflow-driven applications internally use State Pattern concepts.
Common Beginner Mistakes
1. Confusing State with Strategy
Remember:
Strategy = Different algorithms
State = Different object states
2. Keeping Conditional Statements
A common mistake is using State classes while still writing:
if(state == ...)
This defeats the purpose of the pattern.
3. Creating Too Many Tiny States
Only create separate states when behavior genuinely changes.
4. Ignoring State Transitions
Clearly define allowed transitions between states.
Simple Visualization
Without State Pattern:
Context
├── if(Draft)
├── if(Review)
├── if(Published)
└── if(Archived)
With State Pattern:
Context
│
▼
State Interface
▲
│
┌────────┬────────┬─────────┐
│ │ │ │
Draft Review Published Archived
The context delegates behavior to the current state instead of implementing every state itself.
Summary
The State Design Pattern allows an object to change its behavior dynamically when its internal state changes.
By moving state-specific behavior into dedicated state classes, the pattern eliminates large conditional statements and makes systems easier to extend, maintain, and understand.
Whenever an object's behavior depends heavily on its current state and involves multiple state transitions, the State Pattern provides a clean and scalable solution.