State

State

Behavioral pattern

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.

State design pattern structure.
State design pattern structure.

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.
State design pattern sequence diagram
State design pattern sequence diagram
  1. A state by default is set in the Context, this is StateA.
  2. A request operation is executed in the Context, delegating the execution to the current state (StateA).
  3. The Context changes from StateA to StateB.
  4. Again, a request operation is executed in the Context delegating the execution to the current state (StateB).
  5. The execution of StateB results in a change to StateC.
  6. A new request operation is executed in the Context delegating the execution to the current state (StateC).

Real-world example

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.

Discover how the State pattern can help us solve this problem
Discover how the State pattern can help us solve this problem

About this book

Introducción a la arquitectura de software

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
All rights reserved ©