Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
// struct Data may be any kind of data. it may be external or inside the context class.
// states shall have access to this data.
struct Data{
Data(int d) : data1(d){}
int data1;
// the context class may be anything, that has internal states
// and behaves differently depending on the internal state.
// this context class has only one signal for clarity.
// having a hole bunch of signals is common.
class Context{
struct State {//top-level state
virtual void signalA(){}//put code here for signalA in superstate
Data* data;// pointer to data, which physically resides inside the context class (contextdata)
} *statePtr; // a pointer to current state. Used for polymorphism.
struct StateA : public State {
virtual void signalA(){// put code here for transition from A with signalA
data->data1 += 2; // manipulate extended state data
new (this) StateB;// change to state B
struct StateB : public State {
virtual void signalA(){//put code here for state B and signalA. Data may be accessed via data->
if ( data->data1 > 10 ) // choice point
new (this) StateA;
new (this) StateB;
StateA stateMember;//The memory for the state is part of context object
Data contextdata; //Data is also kept inside the context object
: statePtr(&stateMember) // assigning start state
, contextdata(0) // initializing data
statePtr->data = &contextdata; // connecting state->data with the context data
void signalA(){statePtr->signalA();} // context delegates signals to state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment