source: src/Patterns/Observer.cpp@ 9e776f

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

Observable::signOn/Off functions are now on const instance possible.

  • maps of Observable are static anyway.
  • we need some const_casts as instances in maps (which we need as lookup key in sign on/off) are non-const.
  • whether there are more or fewer observers does not impact on the constness of a class but only affects a mutable part.
  • Property mode set to 100644
File size: 14.8 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * Observer.cpp
10 *
11 * Created on: Jan 19, 2010
12 * Author: crueger
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "MemDebug.hpp"
21
22#include "Observer.hpp"
23
24#include <iostream>
25
26#include "Assert.hpp"
27#include "MemDebug.hpp"
28
29using namespace std;
30
31/****************** Static stuff for the observer mechanism ************/
32
33// All infrastructure for the observer-pattern is bundled at a central place
34// this is more efficient if many objects can be observed (inherit from observable)
35// but only few are actually coupled with observers. E.g. TMV has over 500.000 Atoms,
36// which might become observable. Handling Observable infrastructure in each of
37// these would use memory for each atom. By handling Observer-infrastructure
38// here we only need memory for objects that actually are observed.
39// See [Gamma et al, 1995] p. 297
40
41map<Observable*, int> Observable::depth; //!< Map of Observables to the depth of the DAG of Observers
42map<Observable*,multimap<int,Observer*> > Observable::callTable; //!< Table for each Observable of all its Observers
43std::map<Observable*,std::set<Notification*> > Observable::notifications;
44set<Observable*> Observable::busyObservables; //!< Set of Observables that are currently busy notifying their sign-on'ed Observers
45
46/** Attaching Sub-observables to Observables.
47 * Increases entry in Observable::depth for this \a *publisher by one.
48 *
49 * The two functions \sa start_observer_internal() and \sa finish_observer_internal()
50 * have to be used together at all time. Never use these functions directly
51 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
52 * thus producing compiler-errors whenever only one is used.
53 * \param *publisher reference of sub-observable
54 */
55void Observable::start_observer_internal(Observable *publisher){
56 // increase the count for this observable by one
57 // if no entry for this observable is found, an new one is created
58 // by the STL and initialized to 0 (see STL documentation)
59#ifdef LOG_OBSERVER
60 observerLog().addMessage(depth[publisher]) << ">> Locking " << observerLog().getName(publisher) << endl;
61#endif
62 depth[publisher]++;
63}
64
65/** Detaching Sub-observables from Observables.
66 * Decreases entry in Observable::depth for this \a *publisher by one. If zero, we
67 * start notifying all our Observers.
68 *
69 * The two functions start_observer_internal() and finish_observer_internal()
70 * have to be used together at all time. Never use these functions directly
71 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
72 * thus producing compiler-errors whenever only one is used.
73 * \param *publisher reference of sub-observable
74 */
75void Observable::finish_observer_internal(Observable *publisher){
76 // decrease the count for this observable
77 // if zero is reached all observed blocks are done and we can
78 // start to notify our observers
79 --depth[publisher];
80#ifdef LOG_OBSERVER
81 observerLog().addMessage(depth[publisher]) << "<< Unlocking " << observerLog().getName(publisher) << endl;
82#endif
83 if(depth[publisher]){}
84 else{
85 publisher->notifyAll();
86 // this item is done, so we don't have to keep the count with us
87 // save some memory by erasing it
88 depth.erase(publisher);
89 }
90}
91
92void Observable::enque_notification_internal(Observable *publisher, Notification_ptr notification){
93 ASSERT(notification->owner==publisher,"Some object tried to send a notification it does not own");
94 notifications[publisher].insert(notification);
95}
96
97/** Constructor for Observable Protector.
98 * Basically, calls start_observer_internal(). Hence use this class instead of
99 * calling the function directly.
100 *
101 * \param *protege Observable to be protected.
102 */
103Observable::_Observable_protector::_Observable_protector(Observable *_protege) :
104 protege(_protege)
105{
106 start_observer_internal(protege);
107}
108
109Observable::_Observable_protector::_Observable_protector(const _Observable_protector &dest) :
110 protege(dest.protege)
111{
112 start_observer_internal(protege);
113}
114
115/** Destructor for Observable Protector.
116 * Basically, calls finish_observer_internal(). Hence use this class instead of
117 * calling the function directly.
118 *
119 * \param *protege Observable to be protected.
120 */
121Observable::_Observable_protector::~_Observable_protector()
122{
123 finish_observer_internal(protege);
124}
125
126/************* Notification mechanism for observables **************/
127
128/** Notify all Observers of changes.
129 * Puts \a *this into Observable::busyObservables, calls Observer::update() for all in callee_t
130 * and removes from busy list.
131 */
132void Observable::notifyAll() {
133 // we are busy notifying others right now
134 // add ourselves to the list of busy subjects to enable circle detection
135 busyObservables.insert(this);
136 // see if anyone has signed up for observation
137 // and call all observers
138 try {
139 if(callTable.count(this)) {
140 // elements are stored sorted by keys in the multimap
141 // so iterating over it gives us a the callees sorted by
142 // the priorities
143 callees_t callees = callTable[this];
144 callees_t::iterator iter;
145 for(iter=callees.begin();iter!=callees.end();++iter){
146#ifdef LOG_OBSERVER
147 observerLog().addMessage() << "-> Sending update from " << observerLog().getName(this)
148 << " to " << observerLog().getName((*iter).second)
149 << " (priority=" << (*iter).first << ")"<< endl;
150#endif
151 (*iter).second->update(this);
152 }
153 }
154 }
155 ASSERT_NOCATCH("Exception thrown from Observer Update");
156
157 // send out all notifications that need to be done
158
159 notificationSet currentNotifications = notifications[this];
160 for(notificationSet::iterator it = currentNotifications.begin();
161 it != currentNotifications.end();++it){
162 (*it)->notifyAll();
163 }
164
165 notifications.erase(this);
166
167 // done with notification, we can leave the set of busy subjects
168 busyObservables.erase(this);
169}
170
171
172/** Handles passing on updates from sub-Observables.
173 * Mimicks basically the Observer::update() function.
174 *
175 * \param *publisher The \a *this we observe.
176 */
177void Observable::update(Observable *publisher) {
178 // circle detection
179 if(busyObservables.find(this)!=busyObservables.end()) {
180 // somehow a circle was introduced... we were busy notifying our
181 // observers, but still we are called by one of our sub-Observables
182 // we cannot be sure observation will still work at this point
183 ASSERT(0,"Circle detected in observation-graph.\n"
184 "Observation-graph always needs to be a DAG to work correctly!\n"
185 "Please check your observation code and fix this!\n");
186 return;
187 }
188 else {
189 // see if we are in the process of changing ourselves
190 // if we are changing ourselves at the same time our sub-observables change
191 // we do not need to publish all the changes at each time we are called
192 if(depth.find(this)==depth.end()) {
193#ifdef LOG_OBSERVER
194 observerLog().addMessage() << "-* Update from " << observerLog().getName(publisher)
195 << " propagated by " << observerLog().getName(this) << endl;
196#endif
197 notifyAll();
198 }
199 else{
200#ifdef LOG_OBSERVER
201 observerLog().addMessage() << "-| Update from " << observerLog().getName(publisher)
202 << " not propagated by " << observerLog().getName(this) << endl;
203#endif
204 }
205 }
206}
207
208/** Sign on an Observer to this Observable.
209 * Puts \a *target into Observable::callTable list.
210 * \param *target Observer
211 * \param priority number in [-20,20]
212 */
213void Observable::signOn(Observer *target,int priority) const
214{
215 ASSERT(priority>=-20 && priority<=+20, "Priority out of range [-20:+20] when signing on Observer");
216#ifdef LOG_OBSERVER
217 observerLog().addMessage() << "@@ Signing on " << observerLog().getName(target) << " to " << observerLog().getName(const_cast<Observable *>(this)) << endl;
218#endif
219 bool res = false;
220 callees_t &callees = callTable[const_cast<Observable *>(this)];
221
222 callees_t::iterator iter;
223 for(iter=callees.begin();iter!=callees.end();++iter){
224 res |= ((*iter).second == target);
225 }
226 if(!res)
227 callees.insert(pair<int,Observer*>(priority,target));
228}
229
230/** Sign off an Observer from this Observable.
231 * Removes \a *target from Observable::callTable list.
232 * \param *target Observer
233 */
234void Observable::signOff(Observer *target) const
235{
236 ASSERT(callTable.count(const_cast<Observable *>(this)),"SignOff called for an Observable without Observers.");
237#ifdef LOG_OBSERVER
238 observerLog().addMessage() << "** Signing off " << observerLog().getName(target) << " from " << observerLog().getName(const_cast<Observable *>(this)) << endl;
239#endif
240 callees_t &callees = callTable[const_cast<Observable *>(this)];
241
242 callees_t::iterator iter;
243 callees_t::iterator deliter;
244 for(iter=callees.begin();iter!=callees.end();) {
245 if((*iter).second == target) {
246 callees.erase(iter++);
247 }
248 else {
249 ++iter;
250 }
251 }
252 if(callees.empty()){
253 callTable.erase(const_cast<Observable *>(this));
254 }
255}
256
257void Observable::signOn(Observer *target, Notification_ptr notification) const
258{
259 ASSERT(notification->owner==this,
260 "Trying to sign on for a notification that is not provided by this object");
261
262 notification->addObserver(target);
263}
264
265void Observable::signOff(Observer *target, Notification_ptr notification) const
266{
267 ASSERT(notification->owner==this,
268 "Trying to sign off from a notification that is not provided by this object");
269
270 notification->removeObserver(target);
271}
272
273bool Observable::isBlocked() const
274{
275 return depth.count(const_cast<Observable *>(this)) > 0;
276}
277
278Notification_ptr Observable::getChannel(size_t no) const
279{
280 ASSERT(NotificationChannels != NULL,
281 "Observable::getChannel() - observable has no channels.");
282 return NotificationChannels->getChannel(no);
283}
284
285/** Handles sub-observables that just got killed
286 * when an sub-observerable dies we usually don't need to do anything
287 * \param *publisher Sub-Observable.
288 */
289void Observable::subjectKilled(Observable *publisher){
290}
291
292/** Constructor for class Observable.
293 */
294Observable::Observable(string name) :
295 Observer(Observer::BaseConstructor())
296{
297#ifdef LOG_OBSERVER
298 observerLog().addName(this,name);
299 observerLog().addMessage() << "++ Creating Observable " << observerLog().getName(this) << endl;
300#endif
301}
302
303/** Destructor for class Observable.
304 * When an observable is deleted, we let all our observers know. \sa Observable::subjectKilled().
305 */
306Observable::~Observable()
307{
308#ifdef LOG_OBSERVER
309 observerLog().addMessage() << "-- Destroying Observable " << observerLog().getName(this) << endl;
310#endif
311 if(callTable.count(this)) {
312 // delete all entries for this observable
313 callees_t callees = callTable[this];
314 callees_t::iterator iter;
315 for(iter=callees.begin();iter!=callees.end();++iter){
316 (*iter).second->subjectKilled(this);
317 }
318 callTable.erase(this);
319 }
320}
321
322/** Constructor for class Observer.
323 */
324Observer::Observer(string name)
325{
326#ifdef LOG_OBSERVER
327 observerLog().addName(this,name);
328 observerLog().addMessage() << "++ Creating Observer " << observerLog().getName(this) << endl;
329#endif
330}
331
332/**
333 * Base Constructor for class Observer
334 *
335 * only called from Observable Constructor
336 */
337Observer::Observer(Observer::BaseConstructor){
338#ifdef LOG_OBSERVER
339 observerLog().addObservable(this);
340#endif
341}
342
343/** Destructor for class Observer.
344 */
345Observer::~Observer()
346{
347#ifdef LOG_OBSERVER
348 if(!observerLog().isObservable(this)){
349 observerLog().addMessage() << "-- Destroying Observer " << observerLog().getName(this) << endl;
350 }
351#endif
352}
353
354/**
355 * Method for specialized notifications.
356 * Most Observers wont need or use this, so it is implemented
357 * empty in the base case;
358 */
359void Observer::recieveNotification(Observable *publisher, Notification_ptr notification){
360 ASSERT(0,"Notification received by object that did not sign on for it.");
361}
362
363Notification::Notification(Observable *_owner) :
364 owner(_owner), channelno(-1)
365{}
366
367Notification::Notification(Observable *_owner, size_t _channelno) :
368 owner(_owner), channelno(_channelno)
369{}
370
371Notification::~Notification(){}
372
373void Notification::addObserver(Observer *target){
374 targets.insert(target);
375}
376
377void Notification::removeObserver(Observer *target){
378 targets.erase(target);
379}
380
381void Notification::notifyAll(){
382 for(std::set<Observer*>::iterator it=targets.begin();
383 it!=targets.end();++it){
384 (*it)->recieveNotification(owner,this);
385 }
386}
387
388Channels::Channels(Observable *_owner) :
389 owner(_owner)
390{}
391
392Channels::~Channels()
393{
394 // free all present Notifications
395 for(NotificationTypetoRefMap::iterator iter = ChannelMap.begin();
396 !ChannelMap.empty(); iter = ChannelMap.begin()) {
397 delete iter->second;
398 ChannelMap.erase(iter);
399 }
400}
401
402void Channels::addChannel(size_t no)
403{
404 NotificationTypetoRefMap::const_iterator iter = ChannelMap.find(no);
405 ASSERT(iter == ChannelMap.end(),
406 "Channels::addChannel() - channel "+toString(int(no))+" is already present in ChannelMap.");
407 ChannelMap.insert( std::make_pair(no, new Notification(owner, no)) );
408}
409
410void Channels::removeChannel(size_t no)
411{
412 NotificationTypetoRefMap::iterator iter = ChannelMap.find(no);
413 ASSERT(iter != ChannelMap.end(),
414 "Channels::removeChannel() - channel "+toString(int(no))+" not present in ChannelMap.");
415 delete iter->second;
416 ChannelMap.erase(iter);
417}
418
419Notification_ptr Channels::getChannel(size_t no) const
420{
421 NotificationTypetoRefMap::const_iterator iter = ChannelMap.find(no);
422 ASSERT(iter != ChannelMap.end(),
423 "Channels::getChannel() - channel "+toString(int(no))+" not present in ChannelMap.");
424 return iter->second;
425}
426
427size_t Channels::getType(Notification_ptr channel) const
428{
429 return channel->getChannelNo();
430}
431
432
433#ifdef LOG_OBSERVER
434
435/************************* Methods to do logging of the Observer Mechanism *********/
436
437// The log needs to exist fairly early, so we make it construct on first use,
438// and never destroy it
439ObserverLog &observerLog(){
440 // yes, this memory is never freed... we need it around for the whole programm,
441 // so no freeing is possible
442 static ObserverLog *theLog = Memory::ignore(new ObserverLog());
443 return *theLog;
444}
445
446
447ObserverLog::ObserverLog() :
448 count (0)
449{}
450
451ObserverLog::~ObserverLog(){}
452
453string ObserverLog::getLog(){return log.str();}
454
455std::string ObserverLog::getName(void* obj){
456 return names[obj];
457}
458
459bool ObserverLog::isObservable(void* obj){
460 return observables.count(obj);
461}
462
463void ObserverLog::addName(void* obj , string name){
464 stringstream sstr;
465 sstr << name << "_" << count++;
466 names[obj] = sstr.str();
467}
468
469void ObserverLog::addObservable(void* obj){
470 observables.insert(obj);
471}
472
473void ObserverLog::deleteName(void* obj){
474 names.erase(obj);
475}
476
477void ObserverLog::deleteObservable(void* obj){
478 observables.erase(obj);
479}
480
481stringstream &ObserverLog::addMessage(int depth){
482 for(int i=depth;i--;)
483 log << " ";
484 return log;
485}
486
487#endif
Note: See TracBrowser for help on using the repository browser.