通过继承实现状态模式(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;
}
相关推荐
博客18002 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴2 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨2 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4567 天前
C++进阶(1)——前景提要
c++
夜悊7 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴7 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0017 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
LDR0067 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术7 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园7 天前
C++20 Modules 模块详解
java·开发语言·spring