Chain of Responsibility pattern
within a Hierarchical State Machine
This note illustrates a chain of responsibility (CoR) pattern which emerges in hierarchical state machines (HSM).
The state pattern is an object-oriented implementation of a finite state machine. This pattern is described in the GoF book. A hierarchical state machine (HSM) is the next step beyond a flat finite state machine. HSM uses composition to reduce code duplication. HSM allows to factor out common behavior from several substates, and to put it into a superstate. For example, when several substates should have the same reaction to a certain message, this behavior may be moved into their common superstate.
State Configuration
In an HSM, an answer to the question "What's the current state?" is more interesting, compared to a flat state machine. If an active state of an HSM is a part of a composite state, then all of its superstates are active also. We can visualize such state configuration from several perspectives.
State Chart
State Hierarchy
Object Diagram (Instance Diagram)
The relationship between substate and its superstate classes is aggregation. An object for a substate has a pointer to its superstate object. A substate isn't a subclass of its superstate. There's a common abstract base class for all states.
The Chain of Responsibility (CoR) starts at the deepest nested active state and extends through all of its superstates (recall that those superstates are active too). The HSM engine puts each message through the CoR. First, the deepest nested active state evaluates the message. If it doesn't handle the message, then the message is given to the next superstate. And so on, until one of the states handles the message. If none of the active states can handle the message, then the HSM discards the message.