Card 02/ 08
State Pattern Structure: The Class and State Diagrams
A Context delegates to its current State, and each State can replace itself with the next.
State has three participants: a context that callers use, a state interface, and one concrete class per state. This card reads their roles off the Gang of Four's class diagram, then maps a state diagram of a document onto those classes, so you can go from a drawing of a life cycle to the code.
| Participant | Role |
|---|---|
| Context | The object callers use. Holds the current state and passes each request to it, usually passing itself so the state can change it. |
| State | Declares one method for each request whose behaviour depends on the state. |
| ConcreteState | Implements the behaviour for one state, and may replace the context's state with the next one. |
A state diagram draws the same design from the other side: each box is a state, and each arrow is a request that moves the object from one state to another, called a transition. The document's life looks like this.
Each box becomes a ConcreteState class, and each arrow becomes a line in one of those classes that sets the context's state. An arrow leaving Review is written in Review's methods. A request with no arrow out of a state, such as reject in Draft, is a method that does nothing or reports that the request does not apply.
← → move through sections and cards