这个状态机是利用c++的模板类的特性来实现的。
下面直接给出源码
/* statemachine.h*/
#ifndef STM
#define STM
#include
typedef enum EventActionResult { EventFailed, EventProcessedOK };
template
class State
{
public:
char InputEvent;
State
EventActionResult (T::*Action)(char event );
State
};
#define ANY '*'
template
class StateMachine
{
private:
State
State
T * target;
public:
StateMachine()
{}
void Init( T * _target, State
{
init = current = initialState;
target = _target;
}
void Reset()
{
current = init;
}
void ProcessEvent( char event )
{
for( State
{
if( p->InputEvent == event || p->InputEvent == ANY )
{
if( p->Action != NULL )
{
if( EventFailed == (this->target->*(p->Action))( event ) )
{
if( p->ErrorState != NULL )
{
//Only if there's an errorstate defined. Otherwise, just do nothing
this->current = p->ErrorState;
}
return;
}
}
this->current = p->NextState;
return;
}
}
//Event not found. Do nothing
return;
}
};
class App{
public:
//private:
StateMachine
EventActionResult HandleOne(char e);
EventActionResult HandleTwo(char e);
EventActionResult HandleThree(char e);
void HandleEvent(char e);
void Init();
void Start();
};
#endif
/* statemachine.cpp*/
#include "statemachine.h"
#include
#include
#include
using namespace std;
typedef State
extern STATE Main[];
extern STATE One[];
extern STATE Two[];
STATE Main[] =
{
//EVENT, NEXT, ACTION, ERRORSTATE (where to land if there's an error)
{ '1', One, &App::HandleOne, Two },
{ '2', Two, &App::HandleTwo, NULL },
{ 0, NULL, NULL, NULL}, //End of table
};
STATE One[] =
{
{ 'B', Main, &App::HandleThree, NULL },
{ 0, NULL, NULL, NULL },
};
STATE Two[] =
{
{ 'B', Main, NULL, NULL },
{ 0, NULL, NULL, NULL },
};
EventActionResult App::HandleOne(char e)
{
std::cout<<"handleOne"<
}
EventActionResult App::HandleTwo(char e)
{
std::cout<<"HandleTwo"<
}
EventActionResult App::HandleThree(char e){
std::cout<<"HandleThree"<
}
void App::HandleEvent(char e)
{
appStateMachine.ProcessEvent(e);
}
void App::Init()
{
appStateMachine.Init(this, Main);
}
void App::Start()
{
while(1)
{
char event = getchar();
this->HandleEvent(event);
}
}
int main(void)
{
App app;
app.Init();
app.Start();
}
然后g++ statemachine.cpp -o test 就可以编过了
这个状态机框架比较简单,可以按自己需求添加状态和处理函数。
个人水平有限,请各位大佬给出宝贵的意见,初学者看不懂的可以在下面留言我看到了会及时回复的。