软件开发-有限状态机原理及实现

有限状态机(Finite State Machine)又称有限状态自动机或简称状态机,是表示有限个状态以及在这些状态之间的转移和动作等行为的数学模型,由一组状态、一个初始状态、输入和根据输入及现有状态转换为下一个状态的转换函数组成。

typedef struct StateTable

{

int nMessageID;

struct StateTable * (*fun) ();

struct StateTable * pNextState;

}FunctionStateTable;

#define Message1 1

#define Message2 2

#define Message3 3

#define Message4 4

#define Message5 5

#define Message6 6

FunctionStateTable *pState;

extern FunctionStateTable *Function1();

extern FunctionStateTable *Function2();

extern FunctionStateTable *Function3();

extern FunctionStateTable *Function4();

extern FunctionStateTable *Function5();

extern FunctionStateTable *Function6();

FunctionStateTable State3[] =

{

Message5, Function5, NULL,

Message6, Function6, NULL,

};

FunctionStateTable State2[] =

{

Message3, Function3, State3,

Message4, Function4, State3,

};

FunctionStateTable State1[] =

{

Message1, Function1, State2,

Message2, Function2, State2,

};

extern FunctionStateTable State2[];

extern FunctionStateTable State3[];

FunctionStateTable *Function1()

{

printf(“From state1 to state2n”);

return State2;

}

FunctionStateTable *Function2()

{

printf(“From state1 to state2n”);

return State2;

}

FunctionStateTable *Function3()

{

printf(“From state2 to state3n”);

return State3;

}

FunctionStateTable *Function4()

{

printf(“From state2 to state3n”);

return State3;

}

FunctionStateTable *Function5()

{

printf(“Exitn”);

return NULL;

}

FunctionStateTable *Function6()

{

printf(“Exitn”);

return NULL;

}

extern FunctionStateTable *pState;

extern FunctionStateTable State1[];

void HandleMessage(int nMessageID)

{

int i = 0;

for (i = 0; i < 2; i++)

{

if (pState[i].nMessageID == nMessageID)

{

pState[i].fun();

pState = pState[i].pNextState;

break;

}

}

}

int main()

{

pState = State1;

HandleMessage(Message2);

HandleMessage(Message4);

HandleMessage(Message6);

return 0;

}

来源:知识万花筒

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2020年7月3日
下一篇 2020年7月5日

相关推荐