#include <iostream>using namespace Std;class Contex;//Even if it is declared here, if there is a contex function called in the class,//Then the compiler will not find a definition of the place, all here I will//The implementation of all classes is deferred outside, so for each class,//Other classes are visible, the biggest benefit is the mutual invocation between classes//does not produce any undefined type of error warning. Class base{ Public: VirtualvoidChange (Contex*cn)= 0; VirtualvoidPrintfbase ()= 0;}; Class Son1: Publicbase{ Public:voidChange (Contex*cn);voidPrintfbase ();}; Class Son2: Publicbase{ Public:voidChange (Contex*cn);voidPrintfbase ();}; Class Son3: Publicbase{ Public:voidChange (Contex*cn);voidPrintfbase ();}; Class contex{ Public: Contex (Base*b);voidPrintf ();voidChangestate (Base*b);void Do();Private: Base*_b;};voidSon1:: Change(Contex*cn){cn -Changestate (NewSon2 ());}voidSon1::P rintfbase() {cout<< "Son1::P rintfbase ()" <<Endl;}voidSon2:: Change(Contex*cn){cn -Changestate (NewSon3 ());}voidSon2::P rintfbase() {cout<< "Son2::P rintfbase ()" <<Endl;}voidSon3::P rintfbase() {cout<< "Son3::P rintfbase ()" <<Endl;}voidSon3:: Change(Contex*cn){cn -Changestate (NewSon1 ());} Contex:: Contex(Base*b) {_b=b;}voidContex::P rintf()//Here is what the corresponding state should do. {_b -Printfbase ();}voidContex:: Changestate(Base*b) {_b=b;}voidContex::D o(){//Adjust the state, the specific state adjustment is done in the subclass, the final conversion is in the //Complete in the current class. _b -Change (this);} int main () {Base*B= NewSon1 (); Contex*P= NewContex (b); int n= Ten; while(n--) {P -Printf (); P - Do();//Call this function to toggle the state. }return 0;}//state machine is nothing but the state of the switch encapsulated in the class.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
State machine Mode