The state behavioral pattern allows you to simplify your code when you have different modes of operation.

This is really just a specific application of polymorphism. You have a class that needs to performs some action in one of several different ways. Instead of writing all the code to perform the action in each mode, you instead define an interface with all the actions and have your class call through an instance of the interface.

You then declare separate concrete classes that implement the actions in their own way or in their own mode. With these concrete classes, you just need to select one and update the class that wanted to perform the action in the first place to refer to one of the concrete implementations.

The episode describes a command class that implements the ability to move a hero in an adventure game forward. When the hero could only walk, maybe it makes sense for the command to directly implement the code needed to move the hero forward. But when another mode of transport is introduced such as riding a horse, the command class would have to choose between the two different ways of moving forward. This pattern describes how to have the command class call a virtual moveForward method instead. This method will resolve to either walking or riding.

The nice thing about this pattern is that it makes it easy to add more modes. We could add swimming or rowing a boat as additional modes of transport for the hero. In each of these cases, the command to move forward doesn’t have to change or be extended anymore. It just calls the move forward virtual method of the state object.


What's on your mind?

On a scale of 0 to 10, how likely are you to refer us to a friend?