#include <stdio.h>
// 定义状态枚举
typedef enum {
STATE_IDLE,
STATE_RUNNING,
STATE_PAUSED
} State;
// 定义事件枚举
typedef enum {
EVENT_START,
EVENT_STOP,
EVENT_PAUSE,
EVENT_RESUME
} Event;
// 状态机结构体
typedef struct {
State currentState;
} StateMachine;
// 初始化状态机
void initStateMachine(StateMachine *sm) {
sm->currentState = STATE_IDLE;
}
// 状态转移函数
void handleEvent(StateMachine *sm, Event event) {
switch (sm->currentState) {
case STATE_IDLE:
if (event == EVENT_START) {
sm->currentState = STATE_RUNNING;
printf("State changed to RUNNING\n");
}
break;
case STATE_RUNNING:
if (event == EVENT_PAUSE) {
sm->currentState = STATE_PAUSED;
printf("State changed to PAUSED\n");
} else if (event == EVENT_STOP) {
sm->currentState = STATE_IDLE;
printf("State changed to IDLE\n");
}
break;
case STATE_PAUSED:
if (event == EVENT_RESUME) {
sm->currentState = STATE_RUNNING;
printf("State changed to RUNNING\n");
} else if (event == EVENT_STOP) {
sm->currentState = STATE_IDLE;
printf("State changed to IDLE\n");
}
break;
default:
break;
}
}
int main() {
StateMachine sm;
initStateMachine(&sm);
// 模拟事件
handleEvent(&sm, EVENT_START); // IDLE -> RUNNING
handleEvent(&sm, EVENT_PAUSE); // RUNNING -> PAUSED
handleEvent(&sm, EVENT_RESUME); // PAUSED -> RUNNING
handleEvent(&sm, EVENT_STOP); // RUNNING -> IDLE
return 0;
}
|