定时器事件类,采用了PIMPL(pointer to implementation)模式。PIMPL模式是一种常用的“类的接口与实现”进行解耦的方法。pimpl具有如下优点:
1. 降低模块耦合度
2. 降低编译依赖,提高编译速度
3. 接口和实现的分离
另外,在c++头文件中,如果一个类的定义包含了其他类类型的指针成员变量,那么其他类就可以在该头文件中只做申明,在源文件中再包含其他类的定义头文件。例如:
school.h文件中
|
//school.h class Student; class Teacher; class School { ... private: Student* a; Teacher* b; }; |
school.cpp文件中
|
//school.cpp #include “student.h” #include “teacher.h” ... |
TimedEvent类提供接口,TimedEventImpl提供具体实现。用户自定义定时器类,继承TimedEvent类实现event方法。TimedEvent类和TimedEventImpl类相互依赖。
以PeriodHeartbeat类为例,启动定时器流程如下图:
在定时器超时触发调用PeriodHeartbeat的event函数时,在该函数执行过程中,再次调用restart_timer函数,这种情况是提前重启定时器,如图3-1中虚线框标出的部分。如果在PeriodHeartbeat的event函数执行过程中,调用过一次restart_timer函数,再次调用restart_timer函数,那么restart_timer函数直接返回,什么也不做。
简单点说,就是在定时器超时触发执行PeriodHeartbeat的event函数的过程中,多次重复调用restart_timer函数,只有第一次是有效的。
定时器超时触发流程如下图: