有限状态自动机是表示有限个状态以及在这些状态之间的转移和动作等行为的数学模型。
使用有限状态自动机可以将复杂的问题简化,比如TCP状态转换。
以前一直不知道怎么实现,今天突然在网络又看到了,这一次决定要研究一下。
不妨以下面的这个自动机为例:
此图来源于网络,请猛击。
门的状态共有4个: Opened, Closed, Locked, Unlocked。事件也有4种:CloseDoor,LockDoor,OpenDoor,UnlockDoor。
本文先提供一种最基本的完整实现,基于switch结构的。
#include <iostream> #include <iomanip> using namespace std; #include <Windows.h> enum DoorState { STATE_UNKOWN = 0, STATE_OPENED = 1, STATE_CLOSED = 2, STATE_LOCKED = 3, STATE_UNLOCKED = 4 }; const char* DoorStateStr[] = { "STATE_UNKOWN", "STATE_OPENED", "STATE_CLOSED", "STATE_LOCKED", "STATE_UNLOCKED" }; enum DoorEvent { EVENT_UNKOWN = 0, EVENT_OPEN_DOOR = 1, EVENT_CLOSE_DOOR = 2, EVENT_LOCK_DOOR = 3, EVENT_UNLOCK_DOOR = 4 }; const char *DoorEventStr[] = { "EVENT_UNKOWN", "EVENT_OPEN_DOOR", "EVENT_CLOSE_DOOR", "EVENT_LOCK_DOOR", "EVENT_UNLOCK_DOOR" }; struct StateMatchine { DoorState state; }; void OpenedStateSwitch(StateMatchine* me, DoorEvent event); void ClosedStateSwitch(StateMatchine* me, DoorEvent event); void LockedStateSwitch(StateMatchine* me, DoorEvent event); void UnlockedStateSwitch(StateMatchine* me, DoorEvent event); void FSMDistpatch(StateMatchine* me, DoorEvent event) { switch (me->state) { case STATE_OPENED: OpenedStateSwitch(me, event); break; case STATE_CLOSED: ClosedStateSwitch(me, event); break; case STATE_LOCKED: LockedStateSwitch(me, event); break; case STATE_UNLOCKED: UnlockedStateSwitch(me, event); break; default: break; } } void OpenedStateSwitch(StateMatchine* me, DoorEvent event) { switch(event) { case EVENT_CLOSE_DOOR: me->state = STATE_CLOSED; break; default: break; } } void ClosedStateSwitch(StateMatchine* me, DoorEvent event) { switch(event) { case EVENT_LOCK_DOOR: me->state = STATE_LOCKED; break; case EVENT_OPEN_DOOR: me->state = STATE_OPENED; break; default: break; } } void LockedStateSwitch(StateMatchine* me, DoorEvent event) { switch(event) { case EVENT_UNLOCK_DOOR: me->state = STATE_UNLOCKED; break; default: break; } } void UnlockedStateSwitch(StateMatchine* me, DoorEvent event) { switch(event) { case EVENT_OPEN_DOOR: me->state = STATE_OPENED; break; case EVENT_LOCK_DOOR: me->state = STATE_LOCKED; break; default: break; } } int main(int argc, char* argv[]) { DoorState lastStat = STATE_UNKOWN; DoorEvent event = EVENT_UNKOWN; StateMatchine me; me.state = STATE_LOCKED; int index = 0; while(index < 10) { switch(index%4+1) { case 1: event = EVENT_OPEN_DOOR; break; case 2: event = EVENT_CLOSE_DOOR; break; case 3: event = EVENT_LOCK_DOOR; break; case 4: event = EVENT_UNLOCK_DOOR; break; default: break; } index++; lastStat = me.state; FSMDistpatch(&me, event); cout<<setiosflags(ios::left) <<setw(15)<<DoorStateStr[lastStat] <<" - " <<setw(20)<<DoorEventStr[event] <<" - " <<setw(15)<<DoorStateStr[me.state]<<endl; Sleep(1); } return 0; }
另外一种利用State模式的实现将会在下一篇博文中给出。
参考链接:
http://blog.csdn.net/xiexievv/article/details/6733470
http://blog.csdn.net/uyghfjhh/article/details/19651225
有限状态自动机FSM实现(一),布布扣,bubuko.com
原文地址:http://blog.csdn.net/dacxu/article/details/26013773