IBR-DTNSuite  0.10
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, bool detach)
63  {
64  if (!detach)
65  {
66  _processor.process(evt);
67  delete evt;
68 
69  ibrcommon::MutexLock l(_dispatch_lock);
70  _stat_count++;
71  }
72  else
73  {
74  // raise the new event
75  dtn::core::EventSwitch::queue( _processor, evt );
76  }
77  }
78 
79  void _add(EventReceiver *receiver) {
80  ibrcommon::MutexLock l(_dispatch_lock);
81  _receivers.push_back(receiver);
82  }
83 
84  void _remove(const EventReceiver *receiver) {
85  ibrcommon::MutexLock l(_dispatch_lock);
86  for (std::list<EventReceiver*>::iterator iter = _receivers.begin(); iter != _receivers.end(); ++iter)
87  {
88  if ((*iter) == receiver)
89  {
90  _receivers.erase(iter);
91  break;
92  }
93  }
94  }
95 
96  static EventDispatcher<E>& instance() {
97  static EventDispatcher<E> i;
98  return i;
99  }
100 
101  public:
102  virtual ~EventDispatcher() { };
103 
107  static void raise(Event *evt, bool detach = true) {
108  instance()._raise(evt, detach);
109  }
110 
111  static void add(EventReceiver *receiver) {
112  instance()._add(receiver);
113  }
114 
115  static void remove(const EventReceiver *receiver) {
116  instance()._remove(receiver);
117  }
118 
119  static void resetCounter() {
120  instance()._reset();
121  }
122 
123  static size_t getCounter() {
124  return instance()._stat_count;
125  }
126 
127  private:
128  ibrcommon::Mutex _dispatch_lock;
129  std::list<EventReceiver*> _receivers;
130  EventProcessorImpl _processor;
131  size_t _stat_count;
132  };
133  }
134 }
135 
136 #endif /* EVENTDISPATCHER_H_ */