Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:See book
The State design pattern characterizes for changing its behavior depending on the state of the application. To achieve this, it’s necessary to create a series of classes for representing the different states an application can go through, that is, one class for each state of the application.
The components included in the State design pattern are as follows:
- Context: It represents the component subject to changing states, it has its current state as one of its properties. Going back to the vending machine example, this would represent the machine.
- AbstractState: Base class used for generating different states. This works better as an abstract class, instead of as an interface, because it allows us to set behaviors by default and alter the operation on every state.
- ConcreteState: Each one of these components represent a state the application could go through during its execution, which is why we’re going to have a ConcreteState for each possible state. This class must inherit from AbstractState.
- A state by default is set in the Context, this is StateA.
- A request operation is executed in the Context, delegating the execution to the current state (StateA).
- The Context changes from StateA to StateB.
- Again, a request operation is executed in the Context delegating the execution to the current state (StateB).
- The execution of StateB results in a change to StateC.
- A new request operation is executed in the Context delegating the execution to the current state (StateC).
By implementing the State design pattern, we are going to create our own server, which will be control through a series of states. These states will tell the server how to behave under different events, because the same event can provide different results depending on the current state of the server.