前段时间写了篇介绍命令行交互工具,不知道各位有没去看看源码,里边有个写法和前段时间介绍的链表使用很像,这就是等下介绍的表驱编程模式,表驱的核心就是“表格”,在多条件判断的时候会使用到多if嵌套,或者switch语法进行处理,但是这样写有时候也挺麻烦的,在这样的场景下就可以考虑使用表驱编程模式,把需要处理的事件或数据放到对应的表格中,最后就形成了一整个表,就可以进行查表然后进行对应操作,下面举个简单案例:
| 头文件
#include "stdio.h"
#include "stdint.h"
typedef struct
{
void (*fp)(void);
} static_t;
extern static_t static_cmd[];
void shell_ls_cmd(void);
void shell_test_cmd(void);
void shell_test_fp(void);
void handle(void);
void push(void (*fp)(void));
void free(uint8_t select);
| 定义一个表
static_t static_cmd[] =
{
{shell_ls_cmd},
{shell_test_cmd},
{NULL}
};
| 定义回调函数
void shell_ls_cmd(void)
{
printf("ls command
");
}
void shell_test_cmd(void)
{
printf("test command
");
}
void shell_test_fp(void)
{
printf("fp command
");
}
| 遍历表
void handle(void)
{
for (uint8_t i = 0; static_cmd[i].fp != NULL; i++)
{
static_cmd[i].fp();
}
}
| 添加表格
void push(void (*fp)(void))
{
uint8_t i = 0;
// 写法1
for(i = 0; static_cmd[i].fp != NULL; i++){};
// 写法2
/*
while(static_cmd[i].fp != NULL){
i++;
}
*/
static_cmd[i].fp = fp;
static_cmd[i+1].fp = NULL;
}
| 删除表格
void free(uint8_t select)
{
if(static_cmd[select].fp == NULL)
{
return;
}
for (uint8_t i = select; static_cmd[i].fp != NULL; i++)
{
static_cmd[i].fp = static_cmd[i+1].fp;
}
}
| 简单调用
int main()
{
handle();
printf("
");
push(shell_test_fp);
printf("
");
handle();
printf("
");
free(1);
printf("
");
handle();
while (1)
{
/* code */
}
}
| 查看结果

表驱在项目中很常见,适当使用能有效提高代码的可读性,也方便后期维护的迭代!
全部0条评论
快来发表一下你的评论吧 !