需求
状态机就是状态转换,如果只有简单的功能的话,用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