Created
June 18, 2011 08:35
-
-
Save 140am/1032923 to your computer and use it in GitHub Desktop.
python observer pattern example
This file contains 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
import pdb | |
import time | |
import threading | |
class Event(object): | |
pass | |
class Observable(object): | |
def __init__(self): | |
self.callbacks = [] | |
def encode(self): | |
print 'ENCODE' | |
def subscribe(self, callback): | |
self.callbacks.append(callback) | |
def fire(self, **attrs): | |
e = Event() | |
e.source = self | |
for k, v in attrs.iteritems(): | |
setattr(e, k, v) | |
for fn in self.callbacks: | |
fn(e) | |
class Logger(threading.Thread): | |
def __init__(self): | |
print 'init Logger' | |
threading.Thread.__init__(self) | |
def alert(self, event): | |
print 'ALERT', event.msg | |
def run(self): | |
while True: | |
time.sleep(1) | |
log = Logger() | |
#log.start() | |
class Encoder(Observable): | |
def encode(self): | |
print 'adsfasdf' | |
super(Encoder, self).encode() | |
#Log = Observable() | |
t = Encoder() | |
pdb.set_trace() |
This file contains 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
import threading | |
import time | |
import pdb | |
class Downloader(threading.Thread): | |
def run(self): | |
print 'downloading' | |
for i in range(1,5): | |
self.i = i | |
time.sleep(2) | |
print 'unfunf' | |
return 'hello world' | |
class Worker(threading.Thread): | |
def run(self): | |
for i in range(1,5): | |
print 'worker running: %i (%i)' % (i, t.i) | |
time.sleep(1) | |
t.join() | |
print 'done' | |
t = Downloader() | |
t.start() | |
time.sleep(1) | |
t1 = Worker() | |
t1.start() | |
t2 = Worker() | |
t2.start() | |
t3 = Worker() | |
t3.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment