Tutorials Design Patterns Mastery

State Pattern: Managing complex object lifecycles

On this page

The State Pattern

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. It is the sophisticated alternative to a giant, unmaintainable switch statement that checks if (status == Status.Paid) everywhere.

1. Solving "Conditional Hell"

Imagine an Order class. The Cancel() method does something different if the order is 'Pending' vs 'Shipped' vs 'Delivered'. Instead of 20 if statements, we create PendingState and ShippedState classes.

public abstract class OrderState 
{
    public abstract void Cancel(Order context);
}

public class ShippedState : OrderState 
{
    // In this state, cancellation is ILLEGAL!
    public override void Cancel(Order context) => throw new Exception("Already shipped!");
}

2. Why use it?

It follows the **Single Responsibility Principle**. All logic related to the "Shipped" status is in one place. If you want to add a new "Returned" state, you just create one new class. You don't have to find and edit 50 different switch statements across your codebase.

4. Interview Mastery

Q: "How is the State pattern different from the Strategy pattern?"

Architect Answer: "The structure is nearly identical, but the **Intent** is different. In **Strategy**, the client chooses the algorithm and passes it in (e.g., 'Use Zip compression'). In **State**, the object itself manages its transitions automatically behind the scenes (e.g., 'I am now Shipped, so I will now use the Shipped logic'). Strategy is a one-time choice; State is a continuous evolution."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details