SOLID & Design Patterns Interview Question #42

What is the State Pattern?

Structural, Creational & Behavioral Patterns Mid-Level Intermediate

Quick Interview Answer

The State Pattern lets an object change its behavior when its internal state changes by delegating state-specific behavior to separate state objects. This can replace large conditionals that repeatedly check status.

Detailed Explanation

The State Pattern lets an object change its behavior when its internal state changes by delegating state-specific behavior to separate state objects. This can replace large conditionals that repeatedly check status.

It is useful when transitions and behavior vary substantially between states, such as Draft, Approved, Shipped, and Cancelled. Simple status flags do not automatically justify a full State implementation.

Code Example

public interface IOrderState
{
    void Ship(OrderContext context);
    void Cancel(OrderContext context);
}

public class OrderContext
{
    public IOrderState State { get; set; }
}