设计模式——观察者模式(C++11实现)

观察者模式定义对象之间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

C++11实现的观察者模式,内部维护了一个泛型函数列表,观察者只需要将观察者函数注册进来即可,消除了继承导致的强耦合,通知接口使用了可变参数模板,支持任意参数,消除了接口变化的影响。

#include <iostream>
#include <string>
#include <functional>
#include <map>

using namespace std;

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

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

template<typename Func>
class Events: NonCopyable
{
public:
    Events(){}
    ~Events(){}
    
    int Connect(Func&& f)
    {
        return Assgin(f);
    }
    
    int Connect(const Func& f)
    {
        return Assgin(f);
    }
    
    void Disconnect(int key)
    {
        m_connections.erase(key);
    }
    
    template<typename... Args>
    void Notify(Args&&... args)
    {  
        for(auto& it: m_connections)   //通知所有观察者,即执行所有注册的观察函数
        {
            it.second(std::forward<Args>(args)...); 
        }
    }
    
private:
    template<typename F>
    int Assgin(F&& f)
    {
        int k=m_observerId++;
        m_connections.emplace(k,std::forward<F>(f)); //注册观察函数
        return k;
    }
    
    int m_observerId=0;
    std::map<int,Func>m_connections;
};

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

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


int main()
{
    Events<std::function<void(int,int)>> myevent;
    auto key=myevent.Connect(print); //注册观察者
    stA t;
    auto lambdakey=myevent.Connect([&t](int a,int b){t.a=a;t.b=b;});
    std::function<void(int,int)> f =std::bind(&stA::print,&t,std::placeholders::_1,std::placeholders::_2);
    myevent.Connect(f);
    int a=1,b=2;
    myevent.Notify(a,b); //广播所有观察者
    myevent.Disconnect(key); //移除观察者
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值