poco 2:Event

本文详细解析了事件(Event)与委托(Delegate)的区别与联系,并通过代码示例展示了如何在C++中使用事件与委托进行事件监听与触发。重点讨论了事件与通知中心(NotificationCenter)之间的相似性及二者在观察者模式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值