#include <stdio.h> #include <string.h> typedef void (*func_evt_hdl)(); /*ptr*/ typedef struct _task_list_ { int flag; func_evt_hdl handler; }EVT_HDL_NODE; #define TK1 1 #define TK2 2 #define TK3 3 #define TK4 4 #define TK5 5 void task_f1() { printf("welcome to task_f1\n"); } void task_f2() { printf("welcome to task_f2\n"); } void task_f3() { printf("welcome to task_f3\n"); } void task_f4() { printf("welcome to task_f4\n"); } void task_f5() { printf("welcome to task_f5\n"); } static const EVT_HDL_NODE evt_hdl[] = { {TK1,task_f1}, {TK2,task_f2}, {TK3,task_f3}, {TK4,task_f4}, {TK5,task_f5}, }; func_evt_hdl get_handler(int flag) { int i,n; func_evt_hdl target_hdl = NULL; n = sizeof(EVT_HDL_NODE); for(i = 0; i < n; i++) { if(evt_hdl[i].flag == flag) { target_hdl = evt_hdl[i].handler; break; } } return target_hdl; } void expect_function_use(int flag) { func_evt_hdl expect_func = NULL; expect_func = get_handler(flag); if(expect_func == NULL) { printf("get handler failed\n"); return; } (*expect_func)(); } int main(void) { expect_function_use(1); expect_function_use(2); expect_function_use(3); expect_function_use(4); expect_function_use(5); return 0; }
对比一种if/else的格式,该方法可以很灵活,如修改或者增加方法,只需要在
evt_hdl增加即可,不需要修改整体框架查询。
该方案还可以更加优化:
void get_handler_function(int flag,func_evt_hdl target_hdl,int len) { int i; for(i = 0; i < len; i++) { if(evt_hdl[i].flag == flag) { if(evt_hdl[i].handler) (*(evt_hdl[i].handler))(); break; } } } int main(void) { func_evt_hdl target = NULL; int len = sizeof(EVT_HDL_NODE); get_handler_function(4,target,len); return 0; }
则更加简洁。
Life is mess, don't let mess mess us.