source: molecuilder/src/Patterns/Observer.cpp@ 4eee8f

Last change on this file since 4eee8f was 65b413, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Small improvements to Observer code

  • Property mode set to 100644
File size: 9.2 KB
RevLine 
[03d7ac]1/*
2 * Observer.cpp
3 *
4 * Created on: Jan 19, 2010
5 * Author: crueger
6 */
7
8#include "Observer.hpp"
9
10
11#include <iostream>
[239987d]12
13#include "Helpers/Assert.hpp"
[03d7ac]14
15using namespace std;
16
17/****************** Static stuff for the observer mechanism ************/
18
19// All infrastructure for the observer-pattern is bundled at a central place
20// this is more efficient if many objects can be observed (inherit from observable)
21// but only few are actually coupled with observers. E.g. TMV has over 500.000 Atoms,
22// which might become observable. Handling Observerable infrastructure in each of
23// these would use memory for each atom. By handling Observer-infrastructure
24// here we only need memory for objects that actually are observed.
25// See [Gamma et al, 1995] p. 297
26
[36c5cf]27map<Observable*, int> Observable::depth; //!< Map of Observables to the depth of the DAG of Observers
[65b413]28map<Observable*,multimap<int,Observer*> > Observable::callTable; //!< Table for each Observable of all its Observers
[c0332d]29std::map<Observable*,std::set<Notification*> > Observable::notifications;
[36c5cf]30set<Observable*> Observable::busyObservables; //!< Set of Observables that are currently busy notifying their sign-on'ed Observers
[03d7ac]31
[36c5cf]32/** Attaching Sub-observables to Observables.
33 * Increases entry in Observable::depth for this \a *publisher by one.
34 *
35 * The two functions \sa start_observer_internal() and \sa finish_observer_internal()
36 * have to be used together at all time. Never use these functions directly
37 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
38 * thus producing compiler-errors whenever only one is used.
39 * \param *publisher reference of sub-observable
40 */
[03d7ac]41void Observable::start_observer_internal(Observable *publisher){
42 // increase the count for this observable by one
43 // if no entry for this observable is found, an new one is created
44 // by the STL and initialized to 0 (see STL documentation)
45 depth[publisher]++;
46}
47
[36c5cf]48/** Detaching Sub-observables from Observables.
49 * Decreases entry in Observable::depth for this \a *publisher by one. If zero, we
50 * start notifying all our Observers.
51 *
52 * The two functions start_observer_internal() and finish_observer_internal()
53 * have to be used together at all time. Never use these functions directly
54 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
55 * thus producing compiler-errors whenever only one is used.
56 * \param *publisher reference of sub-observable
57 */
[03d7ac]58void Observable::finish_observer_internal(Observable *publisher){
59 // decrease the count for this observable
60 // if zero is reached all observed blocks are done and we can
61 // start to notify our observers
62 if(--(depth[publisher])){}
63 else{
64 publisher->notifyAll();
65 // this item is done, so we don't have to keep the count with us
66 // save some memory by erasing it
67 depth.erase(publisher);
68 }
69}
70
[c0332d]71void Observable::enque_notification_internal(Observable *publisher, Notification_ptr notification){
72 ASSERT(notification->owner==publisher,"Some object tried to send a notification it does not own");
73 notifications[publisher].insert(notification);
74}
75
[36c5cf]76/** Constructor for Observable Protector.
77 * Basically, calls start_observer_internal(). Hence use this class instead of
78 * calling the function directly.
79 *
80 * \param *protege Observable to be protected.
81 */
[bc1fbf]82Observable::_Observable_protector::_Observable_protector(Observable *_protege) :
83 protege(_protege)
84{
85 start_observer_internal(protege);
86}
87
[36c5cf]88/** Destructor for Observable Protector.
89 * Basically, calls finish_observer_internal(). Hence use this class instead of
90 * calling the function directly.
91 *
92 * \param *protege Observable to be protected.
93 */
[bc1fbf]94Observable::_Observable_protector::~_Observable_protector()
95{
96 finish_observer_internal(protege);
97}
98
[03d7ac]99/************* Notification mechanism for observables **************/
100
[36c5cf]101/** Notify all Observers of changes.
102 * Puts \a *this into Observable::busyObservables, calls Observer::update() for all in callee_t
103 * and removes from busy list.
104 */
[65b413]105void Observable::notifyAll() {
[03d7ac]106 // we are busy notifying others right now
107 // add ourselves to the list of busy subjects to enable circle detection
108 busyObservables.insert(this);
109 // see if anyone has signed up for observation
110 // and call all observers
[65b413]111 try {
112 if(callTable.count(this)) {
113 // elements are stored sorted by keys in the multimap
114 // so iterating over it gives us a the callees sorted by
115 // the priorities
116 callees_t callees = callTable[this];
117 callees_t::iterator iter;
118 for(iter=callees.begin();iter!=callees.end();++iter){
119 (*iter).second->update(this);
120 }
[bb9503]121 }
[03d7ac]122 }
[65b413]123 ASSERT_NOCATCH("Exception thrown from Observer Update");
[c0332d]124
125 // send out all notifications that need to be done
126
127 notificationSet currentNotifications = notifications[this];
128 for(notificationSet::iterator it = currentNotifications.begin();
129 it != currentNotifications.end();++it){
130 (*it)->notifyAll();
131 }
132
133 notifications.erase(this);
134
135 // done with notification, we can leave the set of busy subjects
[03d7ac]136 busyObservables.erase(this);
137}
[65b413]138
[03d7ac]139
[36c5cf]140/** Handles passing on updates from sub-Observables.
141 * Mimicks basically the Observer::update() function.
142 *
143 * \param *publisher The \a *this we observe.
144 */
[03d7ac]145void Observable::update(Observable *publisher) {
146 // circle detection
147 if(busyObservables.find(this)!=busyObservables.end()) {
148 // somehow a circle was introduced... we were busy notifying our
149 // observers, but still we are called by one of our sub-Observables
150 // we cannot be sure observation will still work at this point
[239987d]151 ASSERT(0,"Circle detected in observation-graph.\n"
152 "Observation-graph always needs to be a DAG to work correctly!\n"
153 "Please check your observation code and fix this!\n");
[03d7ac]154 return;
155 }
156 else {
157 // see if we are in the process of changing ourselves
158 // if we are changing ourselves at the same time our sub-observables change
159 // we do not need to publish all the changes at each time we are called
160 if(depth.find(this)==depth.end()) {
161 notifyAll();
162 }
163 }
164}
165
[36c5cf]166/** Sign on an Observer to this Observable.
167 * Puts \a *target into Observable::callTable list.
168 * \param *target Observer
169 * \param priority number in [-20,20]
170 */
[bb9503]171void Observable::signOn(Observer *target,int priority) {
[239987d]172 ASSERT(priority>=-20 && priority<=+20, "Priority out of range [-20:+20] when signing on Observer");
[03d7ac]173 bool res = false;
[65b413]174 callees_t &callees = callTable[this];
[bb9503]175
176 callees_t::iterator iter;
[65b413]177 for(iter=callees.begin();iter!=callees.end();++iter){
[03d7ac]178 res |= ((*iter).second == target);
179 }
180 if(!res)
[65b413]181 callees.insert(pair<int,Observer*>(priority,target));
[03d7ac]182}
183
[36c5cf]184/** Sign off an Observer from this Observable.
185 * Removes \a *target from Observable::callTable list.
186 * \param *target Observer
187 */
[03d7ac]188void Observable::signOff(Observer *target) {
[239987d]189 ASSERT(callTable.count(this),"SignOff called for an Observable without Observers.");
[65b413]190 callees_t &callees = callTable[this];
[bb9503]191 callees_t::iterator iter;
[36c5cf]192 callees_t::iterator deliter;
[65b413]193 for(iter=callees.begin();iter!=callees.end();) {
[3db67e]194 if((*iter).second == target) {
[65b413]195 callees.erase(iter++);
[3db67e]196 }
197 else {
198 ++iter;
199 }
[bb9503]200 }
[65b413]201 if(callees.empty()){
[bb9503]202 callTable.erase(this);
[03d7ac]203 }
204}
205
[c0332d]206void Observable::signOn(Observer *target, Notification_ptr notification){
207 ASSERT(notification->owner==this,
208 "Trying to sign on for a notification that is not provided by this object");
209
210 notification->addObserver(target);
211}
212
213void Observable::signOff(Observer *target, Notification_ptr notification){
214 ASSERT(notification->owner==this,
215 "Trying to sign off from a notification that is not provided by this object");
216
217 notification->removeObserver(target);
218}
219
[239987d]220bool Observable::isBlocked(){
221 return depth.count(this) > 0;
222}
223
[36c5cf]224/** Handles sub-observables that just got killed
225 * when an sub-observerable dies we usually don't need to do anything
226 * \param *publisher Sub-Observable.
227 */
[03d7ac]228void Observable::subjectKilled(Observable *publisher){
229}
230
[36c5cf]231/** Constructor for class Observable.
232 */
[03d7ac]233Observable::Observable()
234{}
235
[36c5cf]236/** Destructor for class Observable.
237 * When an observable is deleted, we let all our observers know. \sa Observable::subjectKilled().
238 */
[03d7ac]239Observable::~Observable()
240{
[bb9503]241 if(callTable.count(this)) {
242 // delete all entries for this observable
[65b413]243 callees_t callees = callTable[this];
[bb9503]244 callees_t::iterator iter;
[65b413]245 for(iter=callees.begin();iter!=callees.end();++iter){
[bb9503]246 (*iter).second->subjectKilled(this);
247 }
248 callTable.erase(this);
[03d7ac]249 }
250}
251
[36c5cf]252/** Constructor for class Observer.
253 */
[03d7ac]254Observer::Observer()
255{}
256
[36c5cf]257/** Destructor for class Observer.
258 */
[03d7ac]259Observer::~Observer()
260{}
[c0332d]261
262/**
263 * Method for specialized notifications.
264 * Most Observers wont need or use this, so it is implemented
265 * empty in the base case;
266 */
267void Observer::recieveNotification(Observable *publisher, Notification_ptr notification){
[65b413]268 ASSERT(0,"Notification received by object that did not sign on for it.");
[c0332d]269}
270
271Notification::Notification(Observable *_owner) :
272 owner(_owner)
273{}
274
275Notification::~Notification(){}
276
277void Notification::addObserver(Observer *target){
278 targets.insert(target);
279}
280
281void Notification::removeObserver(Observer *target){
282 targets.erase(target);
283}
284
285void Notification::notifyAll(){
286 for(std::set<Observer*>::iterator it=targets.begin();
287 it!=targets.end();++it){
288 (*it)->recieveNotification(owner,this);
289 }
290}
Note: See TracBrowser for help on using the repository browser.