Storing state history
Before we end the chapter, we should talk about how to keep track of your state machine’s history. This feature isn’t strictly part of the State pattern, but it’s a handy way of automatically assigning the correct next state rather than hardcoding them in each concrete state.
Like the Command pattern undo/redo system from Chapter 8, Binding Actions with the Command Pattern, the Stack
type is going to save us a lot of trouble with this problem. Using Stack
's last-in-first-out (LIFO) functionality, we can push new states onto the stack, which always makes the current state the one on top. This doesn’t do much for the first state, but when we move through state transitions, the stack will continue storing all the previous states underneath the current state. When we want to revert to the previous state or states, we pop the current state off the top and reference the new state that was next in line!
In automata theory...