The State Behavioral Design Pattern is one of the GoF Design Patterns. In his series on the Gang of Four design patterns, John Thompson wrote an article on the State Pattern, which he defines as “an important pattern that allows an object to change its behavior when it’s[sic] internal state changes.”
He opens the article by providing an example of a Vending Machine program that will need the State Pattern to be applied to it. One thing I like about the way he writes his examples is how he uses variable names to make it very readable. He could have just had the states as the integers themselves, but his simple and clever use of variable names has given me ideas of how to make my programs more readable in the future.
In order to transform his Vending Machine program from a “monolithic class” into a more adaptable program, John shows us how to implement the State Pattern. He separates each of the four states of the vending machine into their own classes. They each implement an interface that defines the behaviors of the vending machine. These state classes each detail how they handle the behavior in that state. Finally, the vending machine itself which handles the inventory of the vending machine and has methods a lot of methods to handle changing the state of the machine.
Due to designing the code with this pattern, you can add a new state by creating a new concrete class and modifying the vending machine class to handle it. However the currently written states are closed to modification as well, following Open Closed principle. When you compare the example before and after the State Pattern was applied, it becomes apparent why it is so beneficial to use this pattern when it’s appropriate: it makes your code more open to modification and more easily-understood. You don’t have to spend as much time reading and understanding code under the State Design Pattern, and so it helps make your program easy to maintain, especially when multiple people might be going back to the code later. Having more classes isn’t necessarily a bad thing.