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

输出结果如下:

相关推荐
心情好的小球藻4 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己16 分钟前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y40900122 分钟前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发6 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
阿葱(聪)9 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java9 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展
斯是 陋室9 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net