State pattern: vending machine

Replace a status field and switch statements with one class per state, each deciding what happens next.

Time —Space —Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

The machine holds its current state and forwards every action to it. Each state class handles every action, including invalid ones, and returns the next state. Adding a state means adding a class instead of editing switches all over the code.

Code

public interface IState { IState Insert(decimal c); IState Select(string item); }
public sealed class Idle : IState
{
    public IState Insert(decimal c) => new HasMoney(c);
    public IState Select(string item) => this; // "insert money first"
}
public sealed class HasMoney : IState
{
    readonly decimal _bal; public HasMoney(decimal b) => _bal = b;
    public IState Insert(decimal c) => new HasMoney(_bal + c);
    public IState Select(string item) => Dispense(item, _bal);
}
public class VendingMachine
{
    IState _state = new Idle();
    public void Insert(decimal c) => _state = _state.Insert(c);
}

Tips

In the .NET library

Order lifecycles (Placed, Paid, Shipped, Delivered, Cancelled) are the same pattern in business code.