In this episode, we look at the state pattern. It is a design that uses object-oriented tactics to provide a class with very different functionality based on its current state. I think you will find this to be one that is not often going to be evident in your first pass of a design.
The State Pattern Defined
As always, we will start with the “Gang of Four” intent to set the stage for our discussion.
“Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.”
We have not had many cases of helpers or partner classes in the patterns we have explored so far. This pattern uses a primary (context) and concrete class (state) to help you organize instance states under one umbrella. The examples vary, but the most familiar one is likely a connection (network, database, etc.). In these cases, the connection class has an internal class reference that varies by state. Thus, the implementation behind a method call is passed through to the state class to provide the needed flexibility.
Applying The Pattern
The implementation of this pattern is not too complicated. However, the access/encapsulation piece of the pattern is something you should think through. You probably do not want to create a state that is entirely open, that would likely limit its usefulness. The typical approach to a state is to start with an interface and then extend that to concrete implementation classes. Those implementation classes are what is used to assign a state to an object. Instead of the state being an integer or string code value, this pattern is where we assign an object as the state.
Java, PHP, C#, etc.
This pattern again works the same in almost any language. All you need to do is create an interface and then inherit from it to implement the concrete classes. This sort of approach is supported in all modern languages. Thus, your challenge will be designing it properly rather than language support.