设计模式——状态模式(有限状态机)

来源:互联网 发布:东莞人工智能公司 编辑:程序博客网 时间:2024/05/22 19:59

状态模式适用的情况:一个context对象根据其所处的状态改变其行为。在状态模式中,我们通过创建不同的state对象来表示不同的状态,而context对象则根据不同的state对象表现出不同的行为。状态模式将不同的状态结构化,以避免过多的 if else 和 switch case 等样版代码。

用设计模式中的 状态模式(行为状态) 实现一个简单的状态机(fsm),其中 class Machine 为 context 对象 ,class ONclass OFF 为 state 对象。
可以对比 boost 的 有限状态机库 see link:
http://blog.csdn.net/gw569453350game/article/details/47272833

注: 相比于使用 monobloc 状态机,状态模式能够提高代码的灵活性、可维护性和可重率。so~,如果是比较大的项目,又有很多状态之间的切换,最好是使用状态模式,而不是一个 monobloc 状态机。

#include <iostream>using namespace std;// 该状态机有 on 和 off 两种操作class Machine{  class State *current;  public:    Machine();    void setState(State *s)    {        current = s;    }    void on();    void off();};// State interface, 在这个接口中声明 on 和 off 操作class State{  public:    virtual void on(Machine *m)    {        cout << "   already ON\n";    }    virtual void off(Machine *m)    {        cout << "   already OFF\n";    }};void Machine::on(){  // 如果需要boost fsm的 entry,在state中加入一个entry函数,current->entry(this)  current->on(this);  // here: current->exit(this);}void Machine::off(){  // 如果需要入口函数,goes here~  current->off(this);}// state子类实现具体的 on 和 off 动作class ON: public State{public:    static ON * Instance()    {        if(m==NULL)            m = new ON();        return m;    }    void off(Machine *m);private:    static ON* m;    ON()    {}};void ON::off(Machine *m){  cout << "   going from ON to OFF\n";  m->setState(OFF::Instance());}class OFF: public State{  public:    static OFF * Instance()    {        if(m==NULL)            m = new OFF();        return m;    }    void on(Machine *m);private:    static OFF* m;    OFF()    {}};void OFF::on(Machine *m){    cout << "   going from OFF to ON\n";    m->setState(ON::Instance());}// 设置默认状态为 offMachine::Machine(){  current = OFF::Instance();  cout << '\n';}// initializeOFF* OFF::m = new OFF(); // or OFF* OFF::m =NULL;ON* ON::m = new ON();  // or ON* ON::m = NULL;int main(){  Machine fsm;  int num;  while (1)  {    cout << "Enter 0/1: ";    cin >> num;    if(num == 1)        fsm.on();    else if(num == 0)        fsm.off();  }}

输出结果:

Enter 0/1: 0   already OFFEnter 0/1: 0   already OFFEnter 0/1: 1   going from OFF to ONEnter 0/1: 0   going from ON to OFFEnter 0/1: 1   going from OFF to ONEnter 0/1: 1   already ONEnter 0/1: 1   already ONEnter 0/1: 

好文齐分享:
http://gameprogrammingpatterns.com/state.html

http://www.codeproject.com/Articles/509234/The-State-Design-Pattern-vs-State-Machine

https://sourcemaking.com/design_patterns

0 0
原创粉丝点击