The state pattern
The state design pattern helps you decouple the behavior of an object, often called the context, from its internal state. For each state, the state object will implement the specific behaviors, keeping the context clean and concise.
This design pattern can help transform large switch statements into smaller objects that can perform the underlying specific task.
Let's get started with a simple example of a state machine—a card reader that you can find at a metro station, bus stop, or other public transportation system. From a high-level perspective, these card readers are simple state machines. They follow a simple run loop—wait, detect, read, success or failure—and each state transition is linear. This makes them particularly suitable for demonstrating this pattern.
The card reader
When we think about a finite amount of states, we usually consider using an enum
. While this is not wrong, it forces you to pack all the logic either in your context or your enum
itself. Let's explore...