poco 2:Event

来源:互联网 发布:超人计划软件 编辑:程序博客网 时间:2024/05/20 01:47

2015-01-28 星期三 21:39:28

1、Event时序图


2、Event Class

3、Event Demo

BasicEventTest.cpp

  • testNoDelegate += --> -= --> notify()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void BasicEventTest::testNoDelegate()
{
    int tmp = 0;
    EventArgs args;
 
    assert (_count == 0);
    assert (Void.empty());
    Void.notify(this);
    assert (_count == 0);
 
    Void += delegate(this, &BasicEventTest::onVoid);
    assert (!Void.empty());
    Void -= delegate(this, &BasicEventTest::onVoid);
    assert (Void.empty());
    Void.notify(this);
 
    assert (_count == 0);
    assert (Simple.empty());
    Simple.notify(this, tmp);
    assert (_count == 0);
 
    Simple += delegate(this, &BasicEventTest::onSimple);
    assert (!Simple.empty());
    Simple -= delegate(this, &BasicEventTest::onSimple);
    assert (Simple.empty());
    Simple.notify(this, tmp);
    assert (_count == 0);
 
    ...................
}
  • 其他的 testN略过

    Event Demo 和 Notifications Demo一样,source和target都是同一个object。

4、Event 分析
  • Notifications比较

    NotificationCenter中callback()携带形参Notification,target知晓的是Notification。

    Event中callback()携带形参const void* pSender,target知晓的是pSender。

    Event中callback()的形参EventArgs args也可以类似为Notification。


    从时序图看,可以认为有如下等同

    NotificationCenter == Event(内聚Strategy,Strategy又内聚vector容器

    ObserverN == DelegateN

  NotificationCenter和Event都内聚了vector容器。Event更抽象(有Strategy),更解耦(有全局的delegate() 函数)。

  它们的实现核心就是内聚了vector容器,通过+=/-=(add/remove)来增删关注者(ObserverN/DelegateN),并在

  Notify()中遍历vector iterator来调用关注者的callback()。其实都可以看作是观察者模式的延伸。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "Poco/BasicEvent.h"
#include "Poco/Delegate.h"
#include <iostream>
using Poco::BasicEvent;
using Poco::Delegate;
class Source
{
public:
    BasicEvent<int> theEvent;
    void fireEvent(int n)
    {
        theEvent.notify(this, n);
    }
};
 
class Target
{
public:
    void onEvent(const void* pSender, int& arg)
    {
        std::cout << "onEvent: " << arg << std::endl;
    }
};
 
int main(int argc, char** argv)
{
    Source source;
    Target target;
    source.theEvent += Poco::delegate(&target, &Target::onEvent);
    source.fireEvent(42);
    source.theEvent -= Poco::delegate(&target, &Target::onEvent);
    return 0;
}

0 0
原创粉丝点击