Controlling Behavior with the State Pattern
In the last chapter, we built a decoupled notification system using the Observer pattern. In this chapter, we’ll jump into more game mechanic territory with the State pattern to create an object that can change its behavior based on an internal state value. While the State pattern is a mainstay of AI programming, you’re intimately familiar with state in everyday life – when you’re tired, you sleep; when you’re hungry, you eat; and when you’re happy, you smile. Each internal state triggers a different behavior in the same underlying object, you. Likewise, when you do a load of laundry, the machine goes through different states before finishing the cycle – rinse, wash, spin dry, and drain; same old washing machine, different states. Applied in code, the object appears to change its class when its behavior changes, when it’s really the underlying state that’s updated!
Like the...