Vladimir Yanakiev Vladimir Yanakiev - 2 months ago 6
C++ Question

Transition betweeen states

I have states classes which inherit from

StateI
:

class StateI
{
....
}
class State1:public StateI
{
....
}
class State2:public StateI
{
....
}
... //etc


I can switch between some states. There is checking logic for every transition between 2 states (example from
State1
to
State2
).

In my current design there is a check function for every state in Interface
like:

class StateI
{
virtual bool transitionToState1() =0;
virtual bool transitionToState2() =0;
//etc...
}


the idea of transitionToState1 is to check if transition from current state is possible to state1.
From OOP point of view, this is not correct, because the parent class
StateI
must have knowledge of its children. What would be better solution from OOP point of view ?

Answer

You implement the state design-pattern. This pattern doesn't define who will define the state transition.

Apparently you have opted for an exhaustive check for each state. I understand that the class using the state will see which is the valid transition for the current state and choose it.

An more flexible approach would be to use a function that returns the next state:

class StateI
{
public:
     virtual StateI*  transitionToNext() =0;
     ...
};

of if the states exist already somewhere, a state check:

class StateI
{
public:
     virtual bool checkTransition(const StateI &potential) =0;
     ...
};
Comments