Game Development Reference
In-Depth Information
template <typename T>
friend void AttachEvent(EventID eventId, T* eventHandler);
template <typename T>
friend void DetachEvent(EventID eventId, T* eventHandler);
private:
using EventMap = std::unordered_map<EventID, Event*>;
using EventMapIterator = EventMap::iterator;
EventMap m_eventMap;
void SendEvent(EventID eventId);
void SendEventToHandler(EventID eventId, EventHandler& eventHandler);
bool RegisterEvent(EventID eventId);
void AttachEvent(EventID eventId, EventHandler& eventHandler);
void DetachEvent(EventID eventId, EventHandler& eventHandler);
public:
virtual ~EventManager();
};
The
EventManager
class has an interesting design. The
Event
objects are stored in an
unordered_map
using the
EventID
as a key. There are also private member methods that contain the behavior of the
class:
SendEvent
,
SendEventToHandler
,
RegisterEvent
,
AttachEvent
, and
DetachEvent
. There are also
public friend
methods that are used to wrap these function calls and use template code. I'll show
you the code for the
private
methods first then talk you through how and why the
public friend
functions are used. Listing 21-10 contains the code for the
RegisterEvent
method.
Listing 21-10.
EventManager::RegisterEvent
bool EventManager::RegisterEvent(EventID eventId)
{
bool added = false;
EventMapIterator result = m_eventMap.find(eventId);
if (result == m_eventMap.end())
{
Event* pNewEvent = new Event(eventId);
if (pNewEvent)
{
std::pair<EventID, Event*> newEvent(eventId, pNewEvent);
auto addedIter = m_eventMap.insert(newEvent);
added = addedIter.second;
}
}
assert(added);
return added;
}