-
-
Save stephanpareigis/8dc83dfb0946d90ad81d7da8723faace to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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