涞水县建设局网站,六盘水市诚信网站建设公司,微信官方网站 - 百度-百度,给几个那方面网站网址事件聚合器#xff08;Event Aggregator#xff09;允许不同的组件订阅和发布事件#xff0c;而不需要知道事件的发布者和订阅者是谁#xff0c;模块可在不直接相互引用的情况下通信#xff0c;实现模块间的松耦合。事件聚合器常用于C#语言中#xff0c;以下为C语言的简单…事件聚合器Event Aggregator允许不同的组件订阅和发布事件而不需要知道事件的发布者和订阅者是谁模块可在不直接相互引用的情况下通信实现模块间的松耦合。事件聚合器常用于C#语言中以下为C语言的简单实现。
C事件聚合器的实现
#pragma once
#include map
#include functional
#include vector
#include iostreamclass EventBase
{
};templatetypename TEventArg
class PubSubEvent : public EventBase
{
public:void Sub(std::functionvoid(TEventArg*) action){actions.push_back(action);}void Pub(TEventArg* arg){for (auto action : actions){action(arg);}}private:std::vectorstd::functionvoid(TEventArg*) actions;
};class EventAggregator
{
public:templatetypename Tstatic T* GetEvent(){auto name typeid(T).raw_name();auto itor events.find(name);if (itor ! events.end()){return static_castT*(itor-second);}else{events[name] new T();return static_castT*(events[name]);}}private:static std::mapconst char*, EventBase* events;
};std::mapconst char*, EventBase* EventAggregator::events;
Demo
#include iostream
#include EventAggregator.hclass TestEventArg
{
public:TestEventArg(std::string name){this-name name;}public:std::string name;
};class TestEvent : public PubSubEventTestEventArg
{};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::GetEventTestEvent()-Sub(test);EventAggregator::GetEventTestEvent()-Sub(std::bind(TestClass::DoEvent, testClass, std::placeholders::_1));EventAggregator::GetEventTestEvent()-Pub(new TestEventArg(hello));EventAggregator::GetEventTestEvent()-Pub(new TestEventArg(world));
}