【Demllie C++ Design Pattern】Finite State Machine Learning

需求

状态机就是状态转换,如果只有简单的功能的话,用if-else或者switch就可以解决了,用类来做状态机就把问题弄复杂了!!!但是如果是十分复杂的状态转换的话,还是需要用状态机,把状态转换的隐藏起来,并且各个状态做各自该做的事,会减少混乱!!!


类图

在这里插入图片描述

代码
#include <iostream>
using namespace std;


class StatePointer;
class State {
protected:
	StatePointer* c;
public:
	virtual ~State(){}

	void setStatePointer(StatePointer* _c) { c = _c; }


	virtual void handle() = 0;
	
};


class StatePointer {
private:
	State* s;
public:
	StatePointer(State* _s) {
		s = nullptr;
		trans2(_s);
	}


	//状态转换
	void trans2(State* _s) {
		
		if (s)delete s;
		s = _s;
		s->setStatePointer(this);//将这个StatePointer移动到下一个状态上
	}


	void run() {
		s->handle();
	}
	

};




/*----------------------------------------------------------------*/
/*----------------------------------------------------------------*/
//具体需要各种的状态
class Hovering : public State {
public:
	void handle() {
		cout << "Hovering => handle" << endl;
	}
};
class Runing : public State {
public:
	void handle() {
		cout << "Runing => handle" << endl;
		c->trans2(new Hovering);
	}
};

class Waiting : public State {
public:
	void handle() {
		cout << "Waiting => handle" << endl;
		c->trans2(new Runing);
	}
};





int main(void) {

	//创建一个状态机
	StatePointer* c = new StatePointer(new Waiting);
	c->run();
	c->run();
	c->run();
	c->run();
	delete c;
	return 0;
}





int main(void) {

	//创建一个状态机
	DealState* c = new DealState(new Waiting);
	c->run();
	c->run();
	c->run();
	c->run();
	delete c;
	return 0;
}
结果

每执行一次,状态自动转换一次,终结状态类一定要定义在其他状态类前面!!!

Waiting => handle
Runing => handle
Hovering => handle
Hovering => handle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

念心科道尊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值