1. The simplest way
We will write state machine pattern with this example
For every state machine design, we need a table
There is one class. Each signal is a function. In each function, we check the current state then implement the action supposed to do in that state. In this case, just print some string.
The class for State machine is as below:
class StateMachineSimple{
public:
StateMachineSimple(): mState(STATE_REST){}
void gotobed();
void train();
void wakeup();
private:
enum Estate{
STATE_SLEEP = 0,
STATE_REST,
STATE_WORK
};
int mState;
};
void StateMachineSimple::gotobed(){
switch (mState)
{
case STATE_SLEEP:
printf("Not available\n");
break;
case STATE_REST:
mState = STATE_SLEEP;
printf("sleep\n");
break;
case STATE_WORK:
printf("Not available\n");
break;
default:
break;
}
}
void StateMachineSimple::train(){
switch (mState)
{
case STATE_SLEEP:
printf("Not available\n");
break;
case STATE_REST:
mState = STATE_WORK;
printf("go to work\n");
break;
case STATE_WORK:
mState = STATE_REST;
printf("go home\n");
break;
default:
break;
}
}
void StateMachineSimple::wakeup(){
switch (mState)
{
case STATE_SLEEP:
mState = STATE_REST;
printf("rest\n");
break;
case STATE_REST:
printf("Not available\n");
break;
case STATE_WORK:
printf("Not available\n");
break;
default:
break;
}
}



