State Machine – How Can a Child State Machine Relinquish Control Back to the Parent State Machine?

design-patternsfinite-state machine

My top level state machine has some states and edges. I will call this the parent state machine.

A ----> B ----> C

Any state within the parent state machine can be a state machine too. I will call these children state machines.

           ___________
         /            \
A ----> |  B0->B1->B2  | ----> C
         \____________/

If the parent state machine transitions from A to B, B's state machine takes over. Once B is done running, how should it relinquish control to the parent state machine and transition to state C? Which design pattern do you use?

If you're wondering, I have children state machines within parent state machines because my exact project is quite complex and it is natural to encapsulate the internal workings of a child state.

Best Answer

Every state machine has some sort of event handler and a means to trigger those events. That handler takes as input the existing state and type of event, chooses the new state, and optionally runs some side effect code.

Essentially, while in state B, your main event handler forwards any events it doesn't recognize to B's event handler and remains in state B. When B wants to transition to C, it posts the appropriate event to the main event handler.

Related Topic