Skip to content

Instantly share code, notes, and snippets.

@stephanpareigis
Last active March 5, 2017 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephanpareigis/8dc83dfb0946d90ad81d7da8723faace to your computer and use it in GitHub Desktop.
Save stephanpareigis/8dc83dfb0946d90ad81d7da8723faace to your computer and use it in GitHub Desktop.
// 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{
private:
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;
else
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
public:
Context()
: 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