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

输出结果如下:

相关推荐
cui_ruicheng几秒前
C++ 多态详解(上):概念与语言机制
开发语言·c++
fpcc2 分钟前
并行编程实战——CUDA编程的其它Warp函数
c++·cuda
java1234_小锋4 分钟前
Java高频面试题:说说Redis的内存淘汰策略?
java·开发语言·redis
hope_wisdom5 分钟前
C/C++数据结构之用链表实现队列
c语言·数据结构·c++·链表·队列
podoor6 分钟前
php版本升级后page页面别名调用出错解决方法
开发语言·php·wordpress
Hx_Ma1610 分钟前
播放器逻辑
java·开发语言
lpfasd12312 分钟前
Markdown 导出 Word 文档技术方案
开发语言·c#·word
busideyang13 分钟前
MATLAB vs Rust在嵌入式领域的角色定位
开发语言·matlab·rust
ghie909013 分钟前
蚁群全局最优算法:原理、改进与MATLAB实现
开发语言·算法·matlab
’长谷深风‘15 分钟前
线程函数接口和属性
c语言·开发语言·线程·进程·软件编程