Say I have a very simple data type:
class SimpleObject:
def __init__(self, property):
self.property = property
def update_property(self, value):
self.property = value
And I a special kind of list to store the data type:
class SimpleList(collections.MutableSequence):
def update_useful_property_of_list(self, value):
self.useful_property_of_list = value
And I store them:
simple1 = SimpleObject(1)
simple2 = SimpleObject(2)
simple_list = SimpleList([simple1, simple2])
Is there any way for the SimpleList
object to know when one of the properties of its members changes? For example, how can I get simple_list
to execute self.update_useful_property_of_list()
when something like this happens:
simple1.update_property(3)
As noted in the comments, you are looking for the Observer design pattern. Simplest, way to do it in your example:
class SimpleObject:
def __init__(self, property, propertyChangeObserver = None):
self.property = property
self.propertyChangeObserver = propertyChangeObserver
def registerPropertyChangeObserver(self, propertyChangeObserver):
self.propertyChangeObserver = propertyChangeObserver
def update_property(self, value):
self.property = value
if self.propertyChangeObserver:
self.propertyChangeObserver.simpleObjectPropertyChanged(self)
and:
class SimpleList(collections.MutableSequence):
def __init__(self, collection):
super(SimpleList, self).__init__(collection)
for e in collection:
e.registerPropertyChangeObserver(self)
def simpleObjectPropertyChanged(self, simpleObject):
pass # react to simpleObject.property being changed
Because you've called your property "property" it's hard to demonstrate low coupling here :) I've called the method simpleObjectPropertyChanged
for clarity, but in fact, SimpleList
doesn't have to know that it stores SimpleObject
instances - it only needs to know that they are observable instances. In a similar manner, SimpleObject
doesn't know about SimpleList
- it only knows about some class that needs to observe its state (an observer - hence the name of the pattern).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With