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

输出结果如下:

相关推荐
JAVA学习通34 分钟前
JAVA多线程(8.0)
java·开发语言
Luck_ff081037 分钟前
【Python爬虫详解】第四篇:使用解析库提取网页数据——BeautifuSoup
开发语言·爬虫·python
学渣6765644 分钟前
什么时候使用Python 虚拟环境(venv)而不用conda
开发语言·python·conda
想睡hhh1 小时前
c++STL——stack、queue、priority_queue的模拟实现
开发语言·c++·stl
小鹿鹿啊1 小时前
C语言编程--14.电话号码的字母组合
c语言·开发语言·算法
Sunlight_7771 小时前
第六章 QT基础:6、QT的Qt 时钟编程
开发语言·qt·命令模式
cloues break.1 小时前
C++初阶----模板初阶
java·开发语言·c++
wwww.wwww1 小时前
Qt软件开发-摄像头检测使用软件V1.1
开发语言·c++·qt
共享家95272 小时前
栈相关算法题解题思路与代码实现分享
c++·leetcode
Wendy_robot2 小时前
【前缀和计算和+哈希表查找次数】Leetcode 560. 和为 K 的子数组
c++·算法·leetcode