C++11观察者模式示例

该示例代码采用C11标准,解决以下问题:

  1. 消除了类继承的强耦合方式;
  2. 通知接口使用可变参数模板,支持任意参数;

示例代码

.h文件如下:

cpp 复制代码
#include <functional>
#include <string>
#include <map>

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

.cpp文件如下:

cpp 复制代码
#include <iostream>
#include "C++11_Observer.h"

using namespace std;
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 lamadakey = 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);
    system("pause");
    return 0;
}

输出结果如下:

相关推荐
浪客川3 小时前
Android的SystemUI的启动流程简析
android·开发语言
郝学胜-神的一滴3 小时前
中级OpenGL教程 022:探秘三维世界的血脉传承——物体父子关系与矩阵递归奥义
c++·线性代数·unity·矩阵·游戏引擎·unreal engine·opengl
-银雾鸢尾-4 小时前
C#中的抽象类与抽象方法
开发语言·c#
萧瑟余晖4 小时前
JDK 20 新特性详解
java·开发语言
benchmark_cc4 小时前
如何用 Python 进行多周期 K 线合成与时区对齐?基于 QuantDash 与 Pandas 的量化数据清洗实战(附 GitHub 源码)
开发语言·python·github·盯盘·pandas·quantdash·量化数据
ch0sen1pm4 小时前
刚学完 CAS 原子操作,我花了一晚上写了三个无锁队列
c++
qeen874 小时前
【C++】vector的模拟实现详解(二)
c++·学习·算法·迭代器·stl
2301_794461574 小时前
Activiti/BPMN 2.0 的 4 种网关
java·服务器·开发语言
147API4 小时前
Claude Tag 进入 Slack 后,团队智能体需要哪些任务与审计字段
java·开发语言·数据库
熬夜苦读学习4 小时前
QT_信号和槽
开发语言·qt