IBR-DTNSuite  0.12
EventDispatcher.h
Go to the documentation of this file.
1 /*
2  * EventDispatcher.h
3  *
4  * Created on: 06.12.2012
5  * Author: morgenro
6  */
7 
8 #ifndef EVENTDISPATCHER_H_
9 #define EVENTDISPATCHER_H_
10 
11 #include "core/Event.h"
12 #include "core/EventSwitch.h"
13 #include "core/EventReceiver.h"
14 #include <ibrcommon/thread/Mutex.h>
16 #include <list>
17 
18 namespace dtn
19 {
20  namespace core
21  {
22  template<class E>
24  private:
28  EventDispatcher() : _processor(*this), _stat_count(0)
29  { };
30 
31  class EventProcessorImpl : public EventProcessor {
32  public:
33  EventProcessorImpl(EventDispatcher<E> &dispatcher)
34  : _dispatcher(dispatcher) { };
35 
36  virtual ~EventProcessorImpl() { };
37 
38  void process(const Event *evt)
39  {
40  ibrcommon::MutexLock l(_dispatcher._dispatch_lock);
41  for (std::list<EventReceiver*>::iterator iter = _dispatcher._receivers.begin();
42  iter != _dispatcher._receivers.end(); ++iter)
43  {
44  EventReceiver &receiver = (**iter);
45  receiver.raiseEvent(evt);
46  }
47 
48  _dispatcher._stat_count++;
49  }
50 
51  EventDispatcher<E> &_dispatcher;
52  };
53 
54  void _reset() {
55  ibrcommon::MutexLock l(_dispatch_lock);
56  _stat_count = 0;
57  }
58 
62  void _raise(Event *evt)
63  {
64  _processor.process(evt);
65  delete evt;
66  }
67 
71  void _queue(Event *evt)
72  {
73  // raise the new event
74  dtn::core::EventSwitch::queue( _processor, evt );
75  }
76 
77  void _add(EventReceiver *receiver) {
78  ibrcommon::MutexLock l(_dispatch_lock);
79  _receivers.push_back(receiver);
80  }
81 
82  void _remove(const EventReceiver *receiver) {
83  ibrcommon::MutexLock l(_dispatch_lock);
84  for (std::list<EventReceiver*>::iterator iter = _receivers.begin(); iter != _receivers.end(); ++iter)
85  {
86  if ((*iter) == receiver)
87  {
88  _receivers.erase(iter);
89  break;
90  }
91  }
92  }
93 
94  static EventDispatcher<E>& instance() {
95  static EventDispatcher<E> i;
96  return i;
97  }
98 
99  public:
100  virtual ~EventDispatcher() { };
101 
105  static void raise(Event *evt) {
106  instance()._raise(evt);
107  }
108 
112  static void queue(Event *evt) {
113  instance()._queue(evt);
114  }
115 
116  static void add(EventReceiver *receiver) {
117  instance()._add(receiver);
118  }
119 
120  static void remove(const EventReceiver *receiver) {
121  instance()._remove(receiver);
122  }
123 
124  static void resetCounter() {
125  instance()._reset();
126  }
127 
128  static size_t getCounter() {
129  return instance()._stat_count;
130  }
131 
132  private:
133  ibrcommon::Mutex _dispatch_lock;
134  std::list<EventReceiver*> _receivers;
135  EventProcessorImpl _processor;
136  size_t _stat_count;
137  };
138  }
139 }
140 
141 #endif /* EVENTDISPATCHER_H_ */