source: src/Patterns/Observer.hpp@ bc2698

Last change on this file since bc2698 was bc2698, checked in by Frederik Heber <heber@…>, 14 years ago

NotificationChannels is now static entity.

  • this is in line with the other static entities on Observable that are intended to save memory (before we needed 8 bytes for the pointer in each and every Observable instances, whether it had channels or not.)
  • Modified NOTIFY macro to accomodate for the changes.
  • enhanced documentation of class Notifications.
  • Property mode set to 100644
File size: 9.5 KB
Line 
1/*
2 * Observer.hpp
3 *
4 * Created on: Jan 19, 2010
5 * Author: crueger
6 */
7
8#ifndef OBSERVER_HPP_
9#define OBSERVER_HPP_
10
11// include config.h
12#ifdef HAVE_CONFIG_H
13#include <config.h>
14#endif
15
16#include <map>
17#include <set>
18#include <string>
19#include <sstream>
20
21/**
22 * Basic structure for the observer pattern
23 *
24 * Observers register themselves with the observables to be notified when something changes.
25 * In the Observable code that changes, attributes should be started with OBSERVE;. This macro
26 * locks the observer mechanism while changes are done. At the end of the scope in which the
27 * macro was placed the lock is released. When the last lock is released all changes are
28 * propagated to the observers.
29 *
30 * Each observerable can have sub-observables. When one of these sub-observables changes and
31 * notifies its observers the observable that contains them will also notify its observers.
32 * This passing on of updates is blocked, when the main-observable is in the process of
33 * updating many of its internal sub-observables. This means the update is not passed, if
34 * it is produced while the main-observable itself is within any Observation block.
35 */
36
37// Deactivate any logging when we are not in debug mode
38#ifdef NDEBUG
39#undef LOG_OBSERVER
40#endif
41
42class Channels;
43class Notification;
44class Observable;
45
46// Pointers to notifications are used for unique identification
47// using this typedef makes it hard for others to mess up this
48// identification process
49typedef Notification *const Notification_ptr;
50
51template<class _Set>
52class ObservedIterator;
53
54/**
55 * An Observer is notified by all Observed objects, when anything changes.
56 *
57 * If a simple change is done to an Object the Obervable will call the update() method
58 * of all signed on observers, passing itself as a parameter for identification. The
59 * Observers should then react to the changes and update themselves accordingly.
60 *
61 * If an observed Object is destroyed it will call the subjectKilled() method
62 * of all signed on Observers, again passing itself as a parameter for identification.
63 * The Observers should handle the destruction of an observed Object gracefully, i.e.
64 * set themselves inactive, display something else, etc. There is no need
65 * to sign of from the dying object, since this will be handled by the Observable destructor.
66 */
67class Observer
68{
69 friend class Observable;
70 friend class Notification;
71 template<class> friend class ObservedIterator;
72
73 // indicates the constructor called from Observables
74 struct BaseConstructor{};
75
76public:
77 Observer(BaseConstructor);
78 Observer(std::string);
79 virtual ~Observer();
80
81protected:
82 /**
83 * This method is called upon changes of the Observable
84 */
85 virtual void update(Observable *publisher)=0;
86
87 /**
88 * This method is called when a special named change
89 * of the Observable occured
90 */
91 virtual void recieveNotification(Observable *publisher, Notification_ptr notification);
92
93 /**
94 * This method is called when the observed object is destroyed.
95 */
96 virtual void subjectKilled(Observable *publisher)=0;
97};
98
99/**
100 * An Observable implements all neccessary method for being observed.
101 *
102 * That is, it provides methods for signing on and of from an
103 * Observable that can be used by any observer. The actual
104 * observer-mechanism is handled at a central static place
105 * to avoid memory issues when many observable are around but only few
106 * are actually observed.
107 */
108class Observable : public Observer {
109public:
110 Observable(std::string _name);
111 virtual ~Observable();
112
113 /**
114 * Sign an Observer on to this Observable. The Observer will be notified
115 * whenever something inside the Observable changes. The Observer can
116 * assign itself a priority for the changes in the range of -20:+20.
117 * The Observer with lower priority will be called before the others,
118 * same as with Unix nice-levels. This can be used when an Object
119 * contains other objects that observe it (derived values), and these objects have
120 * to recalculate their states before the changes should be propageted to the
121 * UI. A default priority of 0 should be fine in most cases, since there is
122 * ussually no need to order the update sequence.
123 */
124 virtual void signOn(Observer *target, int priority=0) const;
125
126 /**
127 * Sign of a previously signed on Observer. After this no more
128 * updates will be recieved from that observer.
129 */
130 virtual void signOff(Observer *target) const;
131
132 /**
133 * Sign on for specialized notifications
134 */
135 virtual void signOn(Observer *target, Notification_ptr notification) const;
136
137 /**
138 * Stop receiving a specialized notification
139 */
140 virtual void signOff(Observer *target, Notification_ptr notification) const;
141
142 /**
143 * Ask an Observer if it is currently in a blocked state, i.e. if
144 * Changes are in Progress, that are not yet published.
145 */
146 virtual bool isBlocked() const;
147
148 Notification_ptr getChannel(size_t no) const;
149
150protected:
151 virtual void update(Observable *publisher);
152 virtual void subjectKilled(Observable *publisher);
153
154 virtual void notifyAll();
155protected:
156// Observer mechanism is done from a static central place
157 /**
158 * Internal method.
159 * Do not call directly. Use OBSERVE macro instead
160 */
161 static void start_observer_internal(Observable *publisher);
162 /**
163 * Internal method.
164 * Do not call directly. Use OBSERVE macro instead
165 */
166 static void finish_observer_internal(Observable *publisher);
167
168 static void enque_notification_internal(Observable *publisher, Notification_ptr notification);
169
170 typedef std::map<Observable*, Channels *> ChannelMap;
171 static ChannelMap NotificationChannels;
172
173private:
174 typedef std::multimap<int,Observer*> callees_t;
175 typedef std::set<Notification*> notificationSet;
176 static std::map<Observable*, int> depth;
177 static std::map<Observable*,callees_t> callTable;
178 static std::map<Observable*,notificationSet> notifications;
179 static std::set<Observable*> busyObservables;
180
181 //! @cond
182 // Structure for RAII-Style notification
183public:
184 /**
185 * This structure implements the Observer-mechanism RAII-Idiom.
186 * It triggers certain functions on creation and destruction so that
187 * Observer mechanisms can be linked to scope block.
188 */
189 class _Observable_protector {
190 public:
191 _Observable_protector(Observable *);
192 _Observable_protector(const _Observable_protector&);
193 ~_Observable_protector();
194 private:
195 Observable *protege;
196 };
197 //! @endcond
198};
199
200/** Notifications are sort of news channels of an Observable.
201 * Via the NOTIFY() macro updates can be transmitted in a specific channel.
202 * Observers can subscribe to Notification in much the same way as they can to
203 * the Observable itself. Usually, Notifications are used along
204 * with the usual OBSERVE() macro to generate both the specific and
205 * the global message of change.
206 */
207class Notification {
208 friend class Observable;
209 friend class Channels;
210public:
211 Notification(Observable *_owner);
212 Notification(Observable *_owner, size_t _channelno);
213 virtual ~Notification();
214
215 size_t getChannelNo() const { return channelno; }
216protected:
217
218 void addObserver(Observer *target);
219 void removeObserver(Observer *target);
220
221 void notifyAll();
222private:
223 Observable * const owner;
224 std::set<Observer*> targets;
225 size_t channelno;
226};
227
228/** Channels aggregate all possible Notifications of an Observable.
229 *
230 * Usually, one implements an enumeration of the channel number which is
231 * visible to the outside only.
232 *
233 */
234class Channels {
235public:
236 Channels(Observable *_owner);
237 virtual ~Channels();
238
239 void addChannel(size_t no);
240
241 Notification_ptr getChannel(size_t no) const;
242 size_t getType(Notification_ptr channel) const;
243
244protected:
245 void removeChannel(size_t no);
246
247private:
248 Observable * const owner;
249
250 typedef std::map< size_t, Notification_ptr> NotificationTypetoRefMap;
251
252 NotificationTypetoRefMap ChannelMap;
253};
254
255#ifdef LOG_OBSERVER
256
257/**
258 * This class is used to log the working of the observer mechanism
259 *
260 * TODO: make this conditional dependent on compiler Flag.
261 */
262class ObserverLog{
263 friend class Observable;
264 friend class Observer;
265 template <typename> friend class Cacheable;
266public:
267 ObserverLog();
268 ~ObserverLog();
269 std::string getLog(); // get everything that has been logged
270 std::string getName(void*); // get the name of an actor
271 bool isObservable(void*);
272private:
273 int count; // number to reference each actor in this framework
274 std::map<void*,std::string> names; // List of names assigned to actors
275 std::set<void*> observables; // List of pointers to Observables. Needed to distinguish Observers and Observables
276 void addName(void*, std::string); // Assign a name to an Actor
277 void addObservable(void*);
278 void deleteName(void*); // delete the name of an Actor
279 void deleteObservable(void*);
280 std::stringstream &addMessage(int depth=0); // Add a Message to the logging
281 std::stringstream log; // The internal log object
282};
283
284ObserverLog &observerLog();
285
286#endif
287
288// extra macro is necessary to work with __LINE__
289#define PASTE(a,b) PASTE_HELPER(a,b)
290#define PASTE_HELPER(a,b) a ## b
291#define OBSERVE Observable::_Observable_protector PASTE(_scope_obs_protector_,__LINE__)(this)
292#define NOTIFY(channelno) do{const ChannelMap::const_iterator iter=NotificationChannels.find(this);ASSERT(iter!=NotificationChannels.end(),"NOTIFY() - channel not found.");Observable::enque_notification_internal(this,iter->second->getChannel(channelno));}while(0)
293#define LOCK_OBSERVABLE(observable) Observable::_Observable_protector PASTE(_scope_obs_protector_,__LINE__)(&(observable))
294
295#endif /* OBSERVER_HPP_ */
Note: See TracBrowser for help on using the repository browser.