State pattern is pretty nice solution for solving problems related to changing behavior of some component(class) at runtime, which varies depending on current state of that object. Clients of our class having dynamic behavior have an impression that, upon interaction with that class, it seems like there’s different implementation of that object as of that interaction. There’s no magic involved – we’re just using composition, and our dynamic object just delegates call to State object it encapsulates. Interface of State object defines set of actions (methods) that change behavior of our wrapping class (set of actions that cause system to transition). State implementations are those that are in charge of making transitions from State to State.
Here’s an example of coffee machine, that acts differently based on State it’s currently in. Here, CoffeeMachine is our dynamic class, and it encapsulates instance of our CoffeeMachineState interface. We initially set Off implementation of State when starting our coffee machine. Then, our implementations transition the state, based on different actions being performed.
Go ahead – subscribe for more interesting content to come! 🙂