I understand that the State pattern
can be used to model objects that changes behavior depending on the state and the various states that the Context
can have is encapsulated in concrete classes that represent a State
interface . What I am not clear is how the state transitions happen in this pattern . Do the individual states
know and decide who follows them or is it the Context
that decides which state it will get next ?
From the GOF Design Patterns book (This is there in the Implementation section):
1. Who defines the state transitions? The State pattern does not specify which participant defines the criteria for state transitions. If the criteria are fixed,then they can be implemented entirely in the Context. It is generally more flexible and appropriate, however, to let the State subclasses themselves specify their successor state and when to make the transition. This requires adding an interface to the Context that lets State objects set the Context's current state explicitly.
Decentralizing the transition logic in this way makes it easy to modify or extend the logic by defining new State subclasses. A disadvantage of decentralization is that one State subclass will have knowledge of at least one other, which introduces implementation dependencies between subclasses.