好久没有来论坛了,单片机编程:高内聚低耦合的一种方法:函数类型和函数指针
//计算四边形的周长 #include <stdio.h> #define RECTANGLE 0 //长方形 #define SQUARE 1 //正方形 //多边形 struct polygon{ int type; int length; int width; }; int get_rectangle_cir(struct polygon pygn) { return 2 * (pygn.length + pygn.width); } int get_square_cir(struct polygon pygn) { return 4 * pygn.width; } int (* get_circumference[])(struct polygon pygn) ={get_rectangle_cir, get_square_cir}; #define get_cir(pygn) get_circumference[pygn.type](pygn) int main(void) { struct polygon pygn_rec, pygn_squ; pygn_rec.type = RECTANGLE; pygn_rec.width = 6; pygn_rec.length = 10; pygn_squ.type = SQUARE; pygn_squ.width = 6; printf("get cir rec is: %d\n",get_cir(pygn_rec)); printf("get cir squ is: %d\n",get_cir(pygn_squ)); return 0; } 当调用get_cir(pygn)时,用类型字段pygn.type做索引,从指针数组get_circumference中取出相应的函数指针来调用,也可以达到if ... else ...的效果,但相比之下这种实现更好,每个函数都只做一件事情,而不必用if ... else ...兼顾好几件事情,比如get_rectangle_cir和get_square_cir各做各的,互相独立,而不必把它们的代码都耦合到一个函数中。 汇总: - 所有与模块相关的功能都应集成到单个源文件中,这是高内聚的体现。
- 模块对外提供一个头文件,该文件声明了该模块的所有资源(硬件依赖/宏/常量/变量/函数)。尽量用struct将紧密相关的变量进行集总封装。
- 在源文件中包括自检代码部分,以实现该模块模块的所有自检功能。
- 固件模块的接口应经过精心设计和定义。
- 由于固件取决于硬件,因此需要在源文件头中明确提及硬件的相关性。比如利用宏将硬件依赖转定义,或者利用函数将基本操作进行封装。则在新的架构体系,仅仅需要移植这部分实现即可使用。
- 通常,固件模块可供其他团队成员在其他项目中使用。可能涉及到管理更改,缺陷修复、所有者应维护模块。源文件头应包含“作者”和“版本”信息。
- 固件在某种程度上取决于编译器。源文件头中应声明基于什么开发环境进行过验证,以指定编译器或与IDE相关的信息。
|