I want to implement the GUI as a state machine. I think there are some benefits and some drawbacks of doing this, but this is not the topic of this questions.
After some reading about this I found several ways of modeling a state machine in C++ and I stuck on 2, but I don’t know what method may fit better for GUI modeling.
-
Represent the State Machine as a list of states with following methods:
OnEvent(...);OnEnterState(...);OnExitState(...);
From
StateMachine::OnEvent(...)I forward the event toCurrentState::OnEvent(...)and here the decision to make a transition or not is made. On transition I callCurrentState::OnExitState(...),NewState::OnEnterState()andCurrentState = NewState;With this approach the state will be tightly coupled with actions, but
Statemight get complicated when from one state I can go to multiple states and I have to take different actions for different transitions. -
Represent the state machine as list of transitions with following properties:
InitialStateFinalStateOnEvent(...)DoTransition(...)
From
StateMachine::OnEvent(...)I forward the event to all transitions whereInitialStatehas same value asCurrentStatein the state machine. If the transition condition is met the loop is stopped,DoTransitionmethod is called andCurrentStateset toTransition::FinalState.With this approach
Transitionwill be very simple, but the number of transition count might get very high. Also it will become harder to track what actions will be done when one state receives an event.
What approach do you think is better for GUI modeling. Do you know other representations that may be better for my problem?
Here is a third option:
symbol(see below)OnEventmethod which returns asymbolFrom
StateMachine::OnEvent(...)events are forwarded toState::OnEventwhich returns asymbol– a result of execution.StateMachinethen based on current state and returned symbol decides whetherOnExitStateandOnEnterStateis called for a corresponsing statesExample matrix for 3 states and 3 symbols
In this example if if machine is in any od the states
(0,1,2)andState::OnEventreturns symbol0(first row in the matrix) – it stays in the same stateSecond row says, that if current state is
0and returned symbol is1transition is made to state1. For state1-> state2and for state2-> state0.Similary third row says that for symbol
2, state0-> state2, state1-> state0, state2-> state1The point of this being:
symbolswill likely be much lower than that of states.DB_ERRORdifferently toNETWORK_ERRORyou just change the transition table and don’t touch states implementation.