首页 > 编程知识 正文

有限状态机的设计步骤,设计模式 状态机模式

时间:2023-05-06 05:47:40 阅读:190438 作者:464

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

使用设计模式中的状态模式(操作状态)实现简单的状态机(fsm )。 其中class Machine是上下文对象,class ON和class OFF是state对象。

可与boost的有限状态机库see link:进行比较

3358 blog.csdn.net/GW 569453350 game/article/details/47272833

注:与使用monobloc状态机相比,状态模式提供了更大的代码灵活性、可维护性和可重用性。 so~,对于较大的项目,如果有很多状态之间的切换,建议使用状态模式,而不是monobloc状态机。

# includeiostreamusingnamespacestd; //此状态机包含on和off两种操作class machine { class state * current; 公共:机器(; voidsetstate(state*s ) { current=s; } void on (; void off (; (; //State interface,在此接口上声明打开和关闭操作的class state { public : virtual voidon (machine * m ) cout'alreadyon(n ' ); }virtualvoidoff(machine*m ) cout'alreadyoff(n ' ); }; 将void machine :3360 on (如果需要/boost FSM的entry,则为state添加entry函数,current-entry(this ) current-on ) ) this。 //here :当前导出(this ); }void Machine:off (() /需要入口函数时goeshere~current-off ) this ); }//state子类为具体的on和off动作class on : public state { public : static on * instance (() if ) m==null ) m=new ON ); 返回m; }voidoff(machine*m ); private :静态on * m; ON (); void on :3360关闭(machine * m ) cout'goingfromontooff(n ); m-setstate (off :3360实例) ); } classoff :公共状态{公共:静态关闭* instance () if(m==null ) m=new OFF ) ); 返回m; }voidon(machine*m ); private :静态关闭* m; 关闭(); 语音关闭:3360 On (machine * m ) cout'goingfromofftoon(n ); m-setstate (on :3360实例) ); //设置的默认状态为offMachine:Machine () current=off33603360instance ); cout 'n '; //initialize off * off :3360 m=new off (; //or OFF* OFF:m=NULL; ON* ON:m=new ON (; //or ON* ON:m=NULL; int main () { Machine fsm; int num; wile(1) { cout 'Enter 0/1: cin num; if(num==1) fsm.on ); elseif(num==0) fsm.off ); }} 输出结果:

enter0/1: alreadyoffenter0/1: alreadyoffenter0/1:1 goingfromofftoonenter0/1: goingfromontooffenter0/1333330 1:1 already onenter0/1:1 already onenter0/1:好文齐分享:

http://gameprogrammingpatterns.com/state.html

33558 www.code project.com/articles/509234/the-state-design-pattern-vs-state-machine

3359 source making.com/design _ patterns

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。