State Pattern

Understand what the State pattern is with the help of an example.

We'll cover the following

The State pattern is a specialization of the Strategy pattern where the strategy changes depending on the state of the context.

A strategy can be selected based on different variables such as a configuration property or an input parameter, and once this selection is done, the strategy remains unchanged for the rest of the lifespan of the context object. In the State pattern, instead, the strategy (also called the state in this circumstance) is dynamic and can change during the lifetime of the context, therefore allowing its behavior to adapt depending on its internal state.

The following illustration shows us a representation of the pattern:

Get hands-on with 1200+ tech skills courses.