State

Allows an object to alter its behavior when its internal state changes; it will appear to change its class.

Context

An order progresses through: Draft → Placed → Paid → Shipped → Delivered. In each state, the allowed actions change.

Problem

If you model this with if (status == ...) in each method, you will have giant switches and duplication.

Solution

Each state is a class with its own behavior. The entity delegates to the current state and allows transitions.

#Example in C#

public abstract class OrderState
{
    public virtual void Pay(Order o)   => throw new InvalidOperationException();
    public virtual void Ship(Order o)  => throw new InvalidOperationException();
}

public class Placed   : OrderState { public override void Pay(Order o)  => o.SetState(new Paid()); }
public class Paid     : OrderState { public override void Ship(Order o) => o.SetState(new Shipped()); }
public class Shipped  : OrderState { }

public class Order
{
    private OrderState _state = new Placed();
    public void SetState(OrderState s) => _state = s;
    public void Pay()  => _state.Pay(this);
    public void Ship() => _state.Ship(this);
}
When NOT to use it

If there are only 2-3 states with little differentiated logic: an enum + switch is sufficient.

Tradeoffs
Pro Con
Eliminates if statements and switches More classes
Explicit and testable states Transitions become dispersed

#behavioral #gof #fsm