State
State is a variation of the Strategy pattern where the strategy changes depending on the state of the context. We have seen in the previous section how a strategy can be selected based on different variables such as user preferences, a configuration parameter, and the input provided, and once this selection is done, the strategy stays unchanged for the rest of the lifespan of the context.
Instead, in the State pattern, the strategy (also called state in this circumstance) is dynamic and can change during the lifetime of the context, thus allowing its behavior to adapt depending on its internal state, as shown in the following figure:
Imagine that we have a hotel booking system and an object called Reservation
that models a room reservation. This is a classical situation where we have to adapt the behavior of an object based on its state. Consider the following series of events:
When the reservation is initially created, the user can confirm (using
confirm()
) the reservation; of course...