如何有效避免大量重复的switch分支
最近学习设计模式相关知识,结合前面的DRBD源码分析掌握了表驱动编程模式,这里作一些简单的总结。
先看一段C代码:
typedef int type;typedef void(*draw)(void);
struct shape
{
type t;
draw f;
};
struct rectange
{
type t;
int a;
draw f;
};
struct circle
{
type t;
int r;
draw f;
};
#define T1 0
#define T2 1
#define T3 2
void drawall(shape[] s, int count)
{
for (int i = 0; i != count; i++)
{
switch((s + i)->t)
{
case T1:
((struct shape*)(s + i))->f();
break;
case T2:
((struct rectange*)(s + i))->f();
break;
case T3:
((struct circle*)(s + i))->f();
break;
default:
break;
}
}
}
按照如上思路修改之后的代码应该是类似这样的:
struct base{
type t;
draw f;
};
typedef int type;
typedef void(*draw)(struct base*);
struct shape
{
type t;
draw f;
};
struct rectange
{
type t;
draw f;
int a;
};
struct circle
{
type t;
draw f;
int r;
};
#define T1 0
#define T2 1
#define T3 2
void drawall(struct base[] s, int count)
{
struct base* b = s;
for (int i = 0; i != count; i++)
{
(b + i)->draw(b + i);
}
}
按照表驱动模式进一步改造该代码:
struct config{
type t;
int l;
};
typedef int type;
typedef void(*draw)(struct config*);
void drawshape(struct config*);
void drawsrectange(struct config*);
void drawcircle(struct config*);
#define T1 0
#define T2 1
#define T3 2
draw call_table[] = {
[T1] = {&drawshape},
[T2] = {&drawsrectange},
[T3] = {&drawcircle},
};
void drawall(struct config[] s, int count)
{
draw* d = call_table;
struct config* b = s;
for (int i = 0; i != count; i++)
{
(*(d + (b + i)->t))(b + i);
}
}
这样代码看起来是简洁了,但是可读性降低了不少。
建议继续学习:
- 从Java视角理解CPU上下文切换(Context Switch) (阅读:5524)
- 从 if else 到 switch case 再到抽象 (阅读:2545)
- JavaScript:假如default不是switch的最后一项 (阅读:2160)
- Switch Case中的经典 (阅读:1935)
扫一扫订阅我的微信号:IT技术博客大学习
- 作者:童燕群 来源: 忘我的追寻
- 标签: switch
- 发布时间:2013-10-29 12:21:06
-
[63] find命令的一点注意事项
-
[49] memory prefetch浅析
-
[41] 读书笔记-壹百度:百度十年千倍的29条法则
-
[31] 小屏幕移动设备网页设计注意事项
-
[30] 卡诺模型―设计品质与设计价值的思考
-
[29] Oracle bbed工具的编译
-
[27] 基本排序算法的PHP实现
-
[23] 8大实用又重要Mac使用技巧
-
[21] 在vim保存时获得sudo权限
-
[21] 程序员技术练级攻略