I’m implementing a state pattern in C++ with a context and several states. Each state implements its transition. Here’s a simplified version of what that design could look like:
class Context;
class State
{
public:
State(Context* ctx);
virtual void transition() = 0;
protected:
Context* context;
}
class Context{
public:
void transition();
void setState(State* next);
private:
State* current;
}
class StateA : public State
{
public:
StateA(Context* ctx);
void transition() override;
}
class StateB : public State
{
public:
StateB(Context* ctx);
void transition() override;
}
Context::setState(State* newState)
{
current = newState;
}
Context::transition()
{
current->transition();
}
StateA::transition()
{
context->setState(new StateB(context));
}
StateB::transition()
{
// noop
}
Now, I need to add a new state transition that requires an integer parameter, like this:
StateB::transition(int a) // This doesn't match the base class!
{
if (a > 5)
{
context->setState(new StateA(context));
}
}
I want to avoid rewriting the entire state pattern for this new requirement since 90% of the code remains the same. How can I modify my current implementation to accommodate state transitions with additional parameters while reusing the existing code?
Emile Papillon-Corbeil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.