from RemoteObject import * class MyThread(threading.Thread): """this is a wrapper for threading.Thread that improves the syntax for creating and starting threads. See Appendix A of The Little Book of Semaphores, http://greenteapress.com/semaphores/ """ def __init__(self, target, *args): threading.Thread.__init__(self, target=target, args=args) self.start() class Subject(RemoteObject): """A Subject is an object that keeps track of the Observers watching it. When the state of a subject changes, it notifies each Observer on the list.""" def __init__(self): RemoteObject.__init__(self) self.observers = [] def notify_observers(self): """notify all registered observers when the state of the subject changes""" for observer in self.observers: print 'Notifying', observer try: observer.notify() except: pass # the following methods are intended to be invoked remotely def register(self, name): """register a new Observer (invoked by the Observer)""" observer = ns.get_proxy(name) self.observers.append(observer) class SimpleSubject(Subject): def __init__(self, state=0): """The state of a SimpleSubject is a single integer named 'state' In a real application, the state would be a more elaborate data structure.""" Subject.__init__(self) self.state = 0 # the following methods are intended to be invoked remotely def set_state(self, state): """change the state of the Subject""" print 'New state', state self.state = state MyThread(self.notify_observers) def get_state(self): """get the current state of the Subject""" return self.state ns = NameServer() name = 'bob' sub = SimpleSubject() sub.connect(ns, name) sub.requestLoop()