State Machine Design Pattern

  • It is used when applicability of each operation depends on the state of the system
  • We create an interface for State with all the possible operations
  • All the states implement the interface and in case of unsupported operations:
    • Provide default implementation
    • Throw exception
  • Uses:
    • Vending Machine
classDiagram

class State {
    <<interface>>
    +operation1()
    +operation2()
}

class State1 {
    +operation1()
    +operation2()
}

class State2 {
    +operation1()
    +operation2()
}

State <|-- State1
State <|-- State2