State Machine

Dated Oct 3, 2026; last modified on Sat, 03 Oct 2026

Motivation

Use it when an object’s behavior changes based on its internal state and you have complex state transition rules. It’s the antidote to scattered conditionals checking current state. Each state know which state comes next and what actions are valid.

Sample Code

public interface IVendingMachineState
{
  void InsertCoin(VendingMachine machine);
  void SelectProduct(VendingMachine machine);
  void Dispense(VendingMachine machine);
}

public class NoCoinState : IVendingMachineState
{
  public void InsertCoin(VendingMachine machine) =>
    machine.SetState(new HasCoinState());

  public void SelectProduct(VendingMachine machine) =>
    Console.WriteLine("Insert coin first");

  public void Dispense(VendingMachine machine) =>
    Console.WriteLine("Insert coin first");
}

public class HasCoinState : IVendingMachineState { ... }

public class DispenseState : IVendingMachineState { ... }

public class VendingMachine
{
  private IVendingMachineState _currentState;

  public VendingMachine() => _currentState = new NoCoinState();

  public SetState(IVendingMachineState state) => _currentState = state;

  public void InsertCoin() => _currentState.InsertCoin(this);
  public void SelectProduct() => _currentState.SelectProduct(this);
  public void Dispense() => _currentState.Dispense(this);
}

References

  1. Design Patterns | Hello Interview Low Level Design. www.hellointerview.com . Accessed Oct 3, 2026.