Chain of Responsibility pattern
within a Hierarchical State Machine

Nick Alexeev

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 chart showing the active state configuration
State chart with composite states. Active states shown in bold.

State Hierarchy

State hierarchy tree.  Active states shown in bold
Sate hierarchy tree.

Object Diagram (Instance Diagram)

UML instance diagram (also known as object diagram) showing the active states.  The active state configuration forms a Chain of Responsibility.
I've left out the state objects for inactive states, for brevity. On a small embedded platform, I allocate all state objects statically. The objects for inactive states remain in memory.

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.

References

GoF design patterns: State and Chain of Responsibility
© Copyright 2015, Nick Alexeev