Created
August 12, 2012 17:21
-
-
Save dhilipsiva/3333120 to your computer and use it in GitHub Desktop.
Python Observer Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo(object): | |
def __init__(self): | |
self._bar_observers = [] | |
def add_bar_observer(self, observer): | |
self._bar_observers.append(observer) | |
def notify_bar(self, param): | |
for observer in self._bar_observers: | |
observer(param) | |
def observer(param): | |
print "observer(%s)" % param | |
class Baz(object): | |
def observer(self, param): | |
print "Baz.observer(%s)" % param | |
class CallableClass(object): | |
def __call__(self, param): | |
print "CallableClass.__call__(%s)" % param | |
baz = Baz() | |
foo = Foo() | |
foo.add_bar_observer(observer) # function | |
foo.add_bar_observer(baz.observer) # bound method | |
foo.add_bar_observer(CallableClass()) # callable instance | |
foo.notify_bar(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment