C++事件聚合器

本文介绍了如何在C++中使用EventAggregator实现实时事件的发布和订阅,通过模板类和函数指针,实现不同组件之间的松耦合通信。示例展示了如何创建、订阅和发布事件。
摘要由CSDN通过智能技术生成

事件聚合器(Event Aggregator)允许不同的组件订阅和发布事件,而不需要知道事件的发布者和订阅者是谁,模块可在不直接相互引用的情况下通信,实现模块间的松耦合。事件聚合器常用于C#语言中,以下为C++语言的简单实现。

C++事件聚合器的实现

#pragma once
#include <map>
#include <functional>
#include <vector>
#include <iostream>

class EventBase
{
};

template<typename TEventArg>
class PubSubEvent : public EventBase
{
public:
	void Sub(std::function<void(TEventArg*)> action)
	{
		actions.push_back(action);
	}

	void Pub(TEventArg* arg)
	{
		for (auto action : actions)
		{
			action(arg);
		}
	}

private:
	std::vector<std::function<void(TEventArg*)>> actions;
};

class EventAggregator
{
public:
	template<typename T>
	static T* GetEvent()
	{
		auto name = typeid(T).raw_name();
		auto itor = events.find(name);

		if (itor != events.end())
		{
			return static_cast<T*>(itor->second);
		}
		else
		{
			events[name] = new T();
			return static_cast<T*>(events[name]);
		}
	}

private:
	static std::map<const char*, EventBase*> events;
};

std::map<const char*, EventBase*> EventAggregator::events;


Demo

#include <iostream>
#include "EventAggregator.h"

class TestEventArg
{
public:
	TestEventArg(std::string name)
	{
		this->name = name;
	}

public:
	std::string name;
};

class TestEvent : public PubSubEvent<TestEventArg>
{

};

class TestClass
{
public:
	void DoEvent(TestEventArg* arg)
	{
		std::cout << "TestClass : " << arg->name << std::endl;
	}
};

void test(TestEventArg* arg)
{
	std::cout << arg->name << std::endl;
}

int main()
{
	TestClass testClass;
	
	EventAggregator::GetEvent<TestEvent>()->Sub(test);
	EventAggregator::GetEvent<TestEvent>()->Sub(std::bind(&TestClass::DoEvent, &testClass, std::placeholders::_1));

	EventAggregator::GetEvent<TestEvent>()->Pub(new TestEventArg("hello"));
	EventAggregator::GetEvent<TestEvent>()->Pub(new TestEventArg("world"));
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值