State pattern: vending machine
Replace a status field and switch statements with one class per state, each deciding what happens next.
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
- Signal: the same switch on status appears in many methods.
- Keep data (inventory, coins) in helper classes so state classes stay small.
- States without fields can be shared single instances.
In the .NET library
Order lifecycles (Placed, Paid, Shipped, Delivered, Cancelled) are the same pattern in business code.