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

输出结果如下:

相关推荐
lly202406几秒前
抽象工厂模式
开发语言
一只小松许️3 分钟前
Rust切片、结构体、枚举
开发语言·rust
老歌老听老掉牙20 分钟前
C++使用Qt Charts创建数据可视化图表
c++·qt·信息可视化
陳長生.40 分钟前
JAVA EE_多线程-初阶(二)
java·开发语言·jvm·java-ee
QTX187301 小时前
常见的 JavaScript 框架和库
开发语言·javascript·ecmascript
爽帅_1 小时前
【C++】STL库_stack_queue 的模拟实现
开发语言·c++
maizeman1261 小时前
R语言——获取数据1
开发语言·r语言·数据读取·内置数据集
。。。9041 小时前
C++中,应尽可能将引用形参声明为const
开发语言·c++
云边有个稻草人1 小时前
【C++】第九节—string类(中)——详解+代码示例
开发语言·c++·迭代器·string类·string的常用接口·string的模拟实现·string的经典例题
煤烦恼2 小时前
scala类与集合
java·大数据·开发语言·人工智能·scala