#pragma once
#include<vector>
#include<map>
#include<string>
class EventHandleBase {
public:
virtual void execute() = 0;
};
template<typename Class>
class EventHandler : public EventHandleBase {
typedef void(Class::* _func)(void);
public:
Class* object;
_func function;
EventHandler(Class* obj, _func func) {
object = obj;
function = func;
}
void execute() {
(object->*function)();
}
};
class Event {
typedef std::map<int, EventHandleBase*> EventHandlerMap;
EventHandlerMap handlers;
int count;
public:
template<typename Class>
void addListener(Class* obj, void(Class::* func)(void)) {
handlers[count] = new EventHandler<Class>(obj, func);
count++;
}
void execute() {
for (EventHandlerMap::iterator it = handlers.begin(); it != handlers.end(); it++)
{
it->second->execute();
}
}
};
class EventManager {
struct EventType {
Event* _event;
std::string name;
};
std::vector<EventType> _events;
static EventManager* _Instance;
EventManager() {}
public:
static EventManager* getInstance() {
if (!_Instance)
{
_Instance = new EventManager();
}
return _Instance;
}
void createEvent(std::string name) {
for (std::vector<EventType>::iterator it = _events.begin(); it != _events.end(); ++it) {
EventType e = *it;
if (e.name.compare(name) == 0)
return;
}
EventType e;
e._event = new Event();
e.name = name;
_events.push_back(e);
}
template <typename Class>
bool subscribe(std::string name, Class* obj, void (Class::* func)(void)) {
for (std::vector<EventType>::iterator it = _events.begin(); it != _events.end(); ++it) {
EventType e = *it;
if (e.name.compare(name) == 0) {
e._event->addListener(obj, func);
return true;
}
}
return false;
}
void execute(std::string name) {
for (std::vector<EventType>::iterator it = _events.begin(); it != _events.end(); ++it) {
EventType e = *it;
if (e.name.compare(name) == 0) {
e._event->execute();
}
}
}
};
//EventManager.cpp
EventManager* EventManager::_Instance;
//使用例子
class A
{
public:
void Put()
{
printf("%s\n", Content.c_str());
}
private:
std::string Content = " i am is A";
};
int main()
{
EventManager* p = EventManager::getInstance();
A* a = new A();
p->createEvent("A");
p->subscribe("A", a, &(A::Put));
for (int i = 0; i < 100; i++)
{
p->execute("A");
}
}