C++ 11实现观察者模式

本文介绍了一个不可复制的事件处理类模板,展示了如何使用`std::function`和`lambda表达式`实现事件连接、断开和通知。重点讲解了`NonCopyable`类和`Events`模板类的用法,以及如何通过绑定函数到事件中。
#include "iostream"
#include <map>
#include <string>
#include <functional>

using namespace std;

class NonCopyable
{
  protected:
    NonCopyable() = default;
    ~NonCopyable() = default;

    NonCopyable(const NonCopyable& ) = delete;
    NonCopyable& operator = (const NonCopyable& ) =delete;
};

template<class Func>
class Events : NonCopyable
{
    public:
        Events(){}
        ~Events(){}

        int Connect(Func&& f)
        {
            return Register(f);
        }

        int Connect(const Func& f)
        {
            return Register(f);
        }

        void DisConnect(int key)
        {
            m_connections.erase(key);
        }

        template <class ...Args>
        void Notify(Args&& ...args)
        {
            for(auto& it : m_connections)
            {
                it.second(std::forward<Args>(args)...);
            }
        }
        private:
            template<class F>
            int Register(F&& f)
            {
                int k = m_observerId++;
                m_connections.emplace(k, std::forward<F>(f));
                return k;
            }

        private:
            int m_observerId = 0;
            std::map<int, Func> m_connections;

};

struct Add
{
    int a, b;
    void print(int a, int b)
    {
        cout << "Add a: " << a << "b: " << b <<endl; 
    }
};


void print(int a, int b)
{
    cout << "Func a: " << a << "b: " << b <<endl; 
}


int main()
{
    Events<std::function<void(int,int)>> myEvents;
    
    auto key = myEvents.Connect(print);

    Add add;
    auto addFunc = std::bind(&Add::print, &add, std::placeholders::_1,std::placeholders::_2);
    auto addKey = myEvents.Connect(addFunc);
    auto lamdaKey = myEvents.Connect([&add](int a, int b){
        add.a = a; 
        add.b = b;
        cout << "lamda a: " << a << "b: " << b <<endl; 
    });

    int a = 1;
    int b = 2;
    myEvents.Notify(a,b);
    myEvents.DisConnect(key);
    getchar();
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值