Using state machines

State machines are a powerful pattern that help you decouple states from their transitions and logic. In this section, we have demonstrated the usage of this pattern, replacing enums with structs to encompass state and its transitions.

In order to implement your state machine successfully, you will need to do the following:

  1. Ensure your program logic can be abstracted as a series of states with clear transitions
  2. Identify your context object, which will be passed around each state
  3. Define a proper protocol that will be implemented on each state
  4. Refactor the context object in order to leverage those state objects and the common protocol