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.
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!");
}
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.
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."