摘自https://cloud.tencent.com/developer/article/1358646
常规写法
void msg_proc(const char *msg_type, const char *msg_buf)
{
if (0 == strcmp(msg_type, "inivite"))
{
inivite_fun(msg_buf);
}
else if (0 == strcmp(msg_type, "tring_100"))
{
tring_fun(msg_buf);
}
else if (0 == strcmp(msg_type, "ring_180"))
{
ring_180_fun(msg_buf);
}
else if (0 == strcmp(msg_type, "ring_181"))
{
ring_181_fun(msg_buf);
}
else if (0 == strcmp(msg_type, "ring_182"))
{
ring_182_fun(msg_buf);
}
else if (0 == strcmp(msg_type, "ring_183"))
{
ring_183_fun(msg_buf);
}
else if (0 == strcmp(msg_type, "ok_200"))
{
ok_200_fun(msg_buf);
}
。。。。。。
else if (0 == strcmp(msg_type, "fail_486"))
{
fail_486_fun(msg_buf);
}
else
{
log("未识别的消息类型%s\n", msg_type);
}
}
数据驱动思想
typedef void (*SIP_MSG_FUN)(const char *);
typedef struct __msg_fun_st
{
const char *msg_type;//消息类型
SIP_MSG_FUN fun_ptr;//函数指针
}msg_fun_st;
msg_fun_st msg_flow[] =
{
{"inivite", inivite_fun},
{"tring_100", tring_fun},
{"ring_180", ring_180_fun},
{"ring_181", ring_181_fun},
{"ring_182", ring_182_fun},
{"ring_183", ring_183_fun},
{"ok_200", ok_200_fun},
。。。。。。
{"fail_486", fail_486_fun}
};
void msg_proc(const char *msg_type, const char *msg_buf)
{
int type_num = sizeof(msg_flow) / sizeof(msg_fun_st);
int i = 0;
for (i = 0; i < type_num; i++)
{
if (0 == strcmp(msg_flow[i].msg_type, msg_type))
{
msg_flow[i].fun_ptr(msg_buf);
return ;
}
}
log("未识别的消息类型%s\n", msg_type);
}
conclusion:
- 数据驱动型编程不是一个全新的编程模型,它只是一种设计思路。
- 数据驱动型编程是编最少的代码,写最少的bug。