您的位置:首页 > 娱乐 > 八卦 > 通过继承实现状态模式(C++)

通过继承实现状态模式(C++)

2024/10/6 8:24:57 来源:https://blog.csdn.net/weixin_45778713/article/details/141033425  浏览:    关键词:通过继承实现状态模式(C++)

 注意:先做类的声明和抽象基类的声明

抽象基类的函数方法中引入类,具体方法在类的实现后面声明。

在抽象基类的子类的函数中可以调用类的成员函数。

#include <iostream>using namespace std;class Contex;class state {
public:virtual void Handel( Contex* contex) = 0;
};class Contex {
public:Contex(state* _state) :State(_state) {};void changeState( state* _state){State = _state;}void showState(){if (State != nullptr){State->Handel(this);}}void showNum(){cout << num << endl;}
private:state *State = nullptr;int num = 10;};class state1 :public state {
public:void Handel(Contex* contex) {cout << "状态1" << endl;}
};class state2 :public state {
public:void Handel(Contex* contex) {cout << "状态2" << endl;}
};class state3 :public state {
public:void Handel(Contex* contex) {cout << "状态3" << endl;contex->showNum();}
};int main()
{state *myState1 = new state1();state *myState2 = new state2();Contex *contex = new Contex(myState1);contex->showState();contex->changeState(myState2);contex->showState();state* myState3 = new state3();contex->changeState(myState3);contex->showState();return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com