Especially in gaming, there are lots of object that perform several actions, and it may have a chance that, in a newer version, there is a same kind of object that perform more actions.
For example, there are two similar UIs in the game, one will do the actions in sequence: actionA0, then actionA1, and another one will do: actionB0, actionA0, actionA1, then actionB1. For code reusability these two UI are implemented in two class, the first one is ClassA and another one is ClassB, and ClassB extends Class A to do the action A and B.
In this programming idea, there is a state machine function in ClassA to do the action w.r.t. the state. The state will be increased by 1 after doing an action. ClassB will override this function in order to change the action sequence.
//Consider ClassA with a state function
void ClassA::processState(int state) {
switch(state) {
case 0:
//blablabla
break;
case 1:
//blablabla
break;
}
}
//And a subclass ClassB want to extend that
void ClassB::processState(int state) {
switch(state) {
case 0:
//state 0 of ClassB
case 1:
case 2:
//ClassB [1,2] -> ClassA [0,1]
ClassA::processState(state-1);
break;
case 3:
//state 3 of Class B
break;
}
}
Of cause it’s going to define the sequence in the code, and a better practice may be reading the state information in file, such as P-List or XML, and then run the sequence w.r.t. the file, but it’s not always possible for more complex logic, and this state machine function and achieve the flexibility.





