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

输出结果如下:

相关推荐
木子.李34736 分钟前
排序算法总结(C++)
c++·算法·排序算法
风逸hhh39 分钟前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮1 小时前
Python训练第四十三天
开发语言·python
freyazzr2 小时前
C++八股 | Day2 | atom/函数指针/指针函数/struct、Class/静态局部变量、局部变量、全局变量/强制类型转换
c++
ascarl20102 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc3 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗3 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长3 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao3 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码3 小时前
STL解析——list的使用
开发语言·c++