Poco::BasicEvent
Poco的Event模块都是在.h文件中实现的,全部是用模版实现的。它的作用是当某个事件发生时,一些回调函数可以被执行。首先定义一个事件,然后向这个事件注册一些回调函数,当事件发生时,这些回调函数会依次被执行。事件还提供了优先级,超时,异步执行的机制。高优先级的先执行;如果回调函数自注册之时起,超时时间过了,则不再被执行;异步执行,触发事件动作马上返回,而不用等待回调函数的执行完毕。
类图:

事件中类的相互调用图

在这个模块中,有一个很重要的模版函数delegate,它是对Delegate,Expire,FunctionDelegate的包装,使AbstractDelegate的子类可以以一个抽象的接口注册到Strategy中。
优先级和超时特性所对应的调用关系和上图基本相似,不同点在于:优先级,在向事件注册代理对象时,高优先级的会被插入到策略对象所包含vector容器的前边,从而优先被执行。超时,回调函数所对应的代理对象被notify时,如果超时了,则回调函数不再被执行。这里不再画出所对应的图。
demo:
class BasicEventTest{public: BasicEventTest():_count(1); ~BasicEventTest(); void testSingleDelegate();protected: static void onStaticSimple(const void* pSender, int& i) { BasicEventTest* p = const_cast<BasicEventTest*>(reinterpret_cast<const BasicEventTest*>(pSender)); p->_count++; }private: int _count; Poco::BasicEvent<int> Simple;};void BasicEventTest::testSingleDelegate(){ int tmp = 0; EventArgs args; assert (_count == 0); Simple += delegate(this, &BasicEventTest::onSimple); Simple.notify(this, tmp); assert (_count == 1); // 可以重复触发 Simple.notify(this, tmp); assert (_count == 2); // 可以重复注册,onSimple会被调用两次 Simple += delegate(this, &BasicEventTest::onSimple); Simple.notify(this, tmp); assert (_count == 4); Simple.notify(this, tmp); assert (_count == 6); // 反注册,因为重复注册,所以需要反注册两次 Simple -= delegate(this, &BasicEventTest::onSimple); Simple -= delegate(this, &BasicEventTest::onSimple); // 如果反注册不存在的回调函数,不会产生异常 Simple -= delegate(this, &BasicEventTest::onSimple);}