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

发布于:2024-08-09 ⋅ 阅读:(128) ⋅ 点赞:(0)

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

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

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

#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;
}


网站公告

今日签到

点亮在社区的每一天
去签到