#!/usr/bin/python import sys # ---------------------------------------------------------------- class Observable(list): """ A class of thing that can be observed. When its notifyObservers() method is called with an event, it passes that event on to its observers. """ def addObserver(self, observer): self.append(observer) def notifyObservers(self, event): for observer in self: observer.observeEvent(event) # ---------------------------------------------------------------- class Observer(object): """ A class of thing that observes an Observable. The Observable will calls the Observer's observeEvent() method. """ def __init__(self, name): self.name = name def observeEvent(self, event): sys.stdout.write('=== %s: "%s"\n' % (self.name, event)) # ---------------------------------------------------------------- class GoatDetector(Observable): """ This class notifies all its observers if a string contains the word 'goat'. """ def detect(self, line): if line.find('goat') != -1: self.notifyObservers('goats detected') # ---------------------------------------------------------------- class DuckDetector(Observable): """ This class notifies all its observers if a string contains the word 'duck'. """ def detect(self, line): if line.find('duck') != -1: self.notifyObservers('ducks detected') # MAIN ----------------------------------------------------------- goatD = GoatDetector() duckD = DuckDetector() alice = Observer('Alice') bert = Observer('Bert') chris = Observer('Chris') goatD.addObserver(alice) goatD.addObserver(bert) duckD.addObserver(chris) for line in iter(sys.stdin.readline, ""): # iter/readline for line-buffering goatD.detect(line) duckD.detect(line)