2 from pprint
import pformat
4 class Observer (object):
5 '''Observers receive notify(*attributes) messages from their
6 subjects whenever new data arrives. This notify() message signifies
7 that an observer should update its internal state/view.'''
10 self
.__attribute
_adapter
= {}
14 def set_debug (self
, enabled
):
15 self
.__debug
= enabled
17 def notify (self
, *attributes
):
18 '''Called by the model to notify Observers about changes.'''
19 # We can be notified about multiple attribute changes at once
20 for attr
in attributes
:
22 if attr
not in self
.__subjects
: continue
24 # The model corresponding to attribute
25 model
= self
.__subjects
[attr
]
27 # The new value for updating
28 value
= model
.getattr (attr
)
30 # Allow mapping from model to observer attributes
31 if attr
in self
.__attribute
_adapter
:
32 attr
= self
.__attribute
_adapter
[attr
]
34 # Call the concrete observer's notification method
35 notify
= model
.get_notify()
36 model
.set_notify (False)
38 self
.subject_changed (model
, attr
, value
)
40 model
.set_notify (notify
)
42 if not self
.__debug
: continue
44 print ("Objserver::notify ("
45 + pformat (attributes
) + "):")
49 def subject_changed (self
, model
, attr
, value
):
50 '''This method handles updating of the observer/UI.
51 This must be implemented in each concrete observer class.'''
53 msg
= 'Concrete Observers must override subject_changed().'
54 raise NotImplementedError, msg
56 def add_subject (self
, model
, model_attr
):
57 self
.__subjects
[model_attr
] = model
59 def add_attribute_adapter (self
, model_attr
, observer_attr
):
60 self
.__attribute
_adapter
[model_attr
] = observer_attr