【无标题】

状态机的实现无非就是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;
}
相关推荐
阿让啊1 天前
C语言strtol 函数使用方法
c语言·数据结构·c++·单片机·嵌入式硬件
Florence231 天前
计算机组成原理:GPU架构、并行计算、内存层次结构等
c语言
不吃鱼的羊1 天前
启动文件Startup_vle.c
c语言·开发语言
歪歪1001 天前
qt creator新手入门以及结合sql server数据库开发
c语言·开发语言·后端·qt·数据库开发
凤年徐2 天前
C++类和对象(上):从设计图到摩天大楼的构建艺术
c语言·开发语言·c++·类和对象
CYRUS_STUDIO2 天前
LLVM 不止能编译!自定义 Pass + 定制 clang 实现函数名加密
c语言·c++·llvm
CYRUS_STUDIO2 天前
OLLVM 移植 LLVM 18 实战,轻松实现 C&C++ 代码混淆
c语言·c++·llvm
南山十一少2 天前
STM32CubeMX + HAL 库:基于 I²C 通信的 BMP280气压海拔测量
c语言·stm32·嵌入式硬件
lingran__2 天前
C语言制作扫雷游戏(拓展版赋源码)
c语言·算法·游戏
77qqqiqi2 天前
学习结构体
c语言·学习