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

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

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

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

cpp 复制代码
#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;
}
相关推荐
blasit8 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 天前
信号量和信号
linux·c++