状态机的实现无非就是3个要素:状态,事件,响应。转换成具体的行为就3句话
发生了什么事?
现在系统处在什么状态?
在这样的状态下发生了这样的事,系统要干什么?
举例--工作管理系统
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义状态枚举
typedef enum {
STATE_IDLE,
STATE_WORKING,
STATE_DONE,
STATE_ERROR
} ToolState;
// 定义状态机结构体
typedef struct {
ToolState currentState;
} ToolStateMachine;
// 状态转换函数
void transitionToIdle(ToolStateMachine *sm)
{
sm->currentState = STATE_IDLE;
printf("Tool is idle.\n");
}
void transitionToWorking(ToolStateMachine *sm) {
sm->currentState = STATE_WORKING;
printf("Tool is working.\n");
// 在这里执行实际的工作
}
void transitionToDone(ToolStateMachine *sm) {
sm->currentState = STATE_DONE;
printf("Tool is done.\n");
}
void transitionToError(ToolStateMachine *sm) {
sm->currentState = STATE_ERROR;
printf("Tool encountered an error.\n");
}
// 处理用户输入的函数
void processInput(ToolStateMachine *sm, const char *input)
{
if(strcmp(input, "start")==0)
{
if(sm->currentState == STATE_IDLE)
{
transitionToWorking(sm);
}
else
{
printf("Cannot start while not in idle state.\n");
}
}
else if(strcmp(input,"stop")==0)
{
if(sm->currentState == STATE_WORKING)
{
transitionToDone(sm);
}
else
{
printf("Cannot stop while not working.\n");
}
}
else if(strcmp(input,"invalid")==0)
{
transitionToError(sm);
}
else
{
printf("Unknown command.\n");
}
}
int main(void)
{
ToolStateMachine sm = {STATE_IDLE};
//模拟用户输入
processInput(&sm,"start");
processInput(&sm,"invalid");
processInput(&sm,"stop");
return 0;
}