The observer pattern in the very simplified code below works well. I would like to have have a decorator @on_event
that does the registration in the Observable singleton.
In class O2 below this does not work. The problem is of course that the decorator on_event get's called prior to the instance is created, and the registration will be to the unbound method event
. In some way I have to delay the registration until the O2 object is initialized. Maybe needless to say but all I want to add in O2 is the decorator as in the code below.
But for sure there must be a solution to this? I have googled around but cannot find anything, and have tried several approaches.
class Observable(object):
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
cls._instance = Observable()
return cls._instance
def __init__(self):
self.obs = []
def event(self, data):
for fn in self.obs:
fn(data)
def on_event(f):
def wrapper(*args):
return f(*args)
Observable.instance().obs.append(f)
return wrapper
class O(object):
def __init__(self, name):
self.name = name
Observable.instance().obs.append(self.event)
def event(self, data):
print self.name + " Event: " + data
class O2(object):
def __init__(self, name):
self.name = name
@on_event
def eventx(self, data):
print self.name + " Event: " + data
if __name__ == "__main__":
o1 = O("o1")
Observable.instance().event("E1")
o2 = O2("o2")
Observable.instance().event("E2")