State machine Mode

Source: Internet
Author: User

#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.