carfield.com.hk Adapter.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c07:Adapter.py # Variations on the Adapter pattern. class WhatIHave: def g(self): pass def h(self): pass class WhatIWant: def f(self): pass class ProxyAdapter(WhatIWant): def __init__(self, whatIHave): self.whatIHave = whatIHave def f(self): # Implement behavior using # methods in WhatIHave: self.whatIHave.g() self.whatIHave.h() class WhatIUse: def op(self, whatIWant): whatIWant.f() # Approach 2: build adapter use into op(): class WhatIUse2(WhatIUse): def op(self, whatIHave): ProxyAdapter(whatIHave).f() # Approach 3: build adapter into WhatIHave: class WhatIHave2(WhatIHave, WhatIWant): def f(self): self.g() self.h() # Approach 4: use an inner class: class WhatIHave3(WhatIHave): class InnerAdapter(WhatIWant): def __init__(self, outer): self.outer = outer def f(self): self.outer.g() self.outer.h() def whatIWant(self): return WhatIHave3.InnerAdapter(self) whatIUse = WhatIUse() whatIHave = WhatIHave() adapt= ProxyAdapter(whatIHave) whatIUse2 = WhatIUse2() whatIHave2 = WhatIHave2() whatIHave3 = WhatIHave3() whatIUse.op(adapt) # Approach 2: whatIUse2.op(whatIHave) # Approach 3: whatIUse.op(whatIHave2) # Approach 4: whatIUse.op(whatIHave3.whatIWant()) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z ChainOfResponsibility.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c06:ChainOfResponsibility.py # Carry the information into the strategy: class Messenger: pass # The Result object carries the result data and # whether the strategy was successful: class Result: def __init__(self): self.succeeded = 0 def isSuccessful(self): return self.succeeded def setSuccessful(self, succeeded): self.succeeded = succeeded class Strategy: def __call__(messenger): pass def __str__(self): return &quot;Trying &quot; + self.__class__.__name__ \ + &quot; algorithm&quot; # Manage the movement through the chain and # find a successful result: class ChainLink: def __init__(self, chain, strategy): self.strategy = strategy self.chain = chain self.chain.append(self) def next(self): # Where this link is in the chain: location = self.chain.index(self) if not self.end(): return self.chain[location + 1] def end(self): return (self.chain.index(self) + 1 &gt;= len(self.chain)) def __call__(self, messenger): r = self.strategy(messenger) if r.isSuccessful() or self.end(): return r return self.next()(messenger) # For this example, the Messenger # and Result can be the same type: class LineData(Result, Messenger): def __init__(self, data): self.data = data def __str__(self): return `self.data` class LeastSquares(Strategy): def __call__(self, messenger): print self linedata = messenger # [ Actual test/calculation here ] result = LineData([1.1, 2.2]) # Dummy data result.setSuccessful(0) return result class NewtonsMethod(Strategy): def __call__(self, messenger): print self linedata = messenger # [ Actual test/calculation here ] result = LineData([3.3, 4.4]) # Dummy data result.setSuccessful(0) return result class Bisection(Strategy): def __call__(self, messenger): print self linedata = messenger # [ Actual test/calculation here ] result = LineData([5.5, 6.6]) # Dummy data result.setSuccessful(1) return result class ConjugateGradient(Strategy): def __call__(self, messenger): print self linedata = messenger # [ Actual test/calculation here ] result = LineData([7.7, 8.8]) # Dummy data result.setSuccessful(1) return result solutions = [] solutions = [ ChainLink(solutions, LeastSquares()), ChainLink(solutions, NewtonsMethod()), ChainLink(solutions, Bisection()), ChainLink(solutions, ConjugateGradient()) ] line = LineData([ 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 ]) print solutions[0](line) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z CoffeeShop.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: cX:decorator:nodecorators:CoffeeShop.py # Coffee example with no decorators class Espresso: pass class DoubleEspresso: pass class EspressoConPanna: pass class Cappuccino: def __init__(self): self.cost = 1 self.description = &quot;Cappucino&quot; def getCost(self): return self.cost def getDescription(self): return self.description class CappuccinoDecaf: pass class CappuccinoDecafWhipped: pass class CappuccinoDry: pass class CappuccinoDryWhipped: pass class CappuccinoExtraEspresso: pass class CappuccinoExtraEspressoWhipped: pass class CappuccinoWhipped: pass class CafeMocha: pass class CafeMochaDecaf: pass class CafeMochaDecafWhipped: def __init__(self): self.cost = 1.25 self.description = \ &quot;Cafe Mocha decaf whipped cream&quot; def getCost(self): return self.cost def getDescription(self): return self.description class CafeMochaExtraEspresso: pass class CafeMochaExtraEspressoWhipped: pass class CafeMochaWet: pass class CafeMochaWetWhipped: pass class CafeMochaWhipped: pass class CafeLatte: pass class CafeLatteDecaf: pass class CafeLatteDecafWhipped: pass class CafeLatteExtraEspresso: pass class CafeLatteExtraEspressoWhipped: pass class CafeLatteWet: pass class CafeLatteWetWhipped: pass class CafeLatteWhipped: pass cappuccino = Cappuccino() print (cappuccino.getDescription() + &quot;: $&quot; + `cappuccino.getCost()`) cafeMocha = CafeMochaDecafWhipped() print (cafeMocha.getDescription() + &quot;: $&quot; + `cafeMocha.getCost()`) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z CommandPattern.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c06:CommandPattern.py class Command: def execute(self): pass class Loony(Command): def execute(self): print &quot;You're a loony.&quot; class NewBrain(Command): def execute(self): print &quot;You might even need a new brain.&quot; class Afford(Command): def execute(self): print &quot;I couldn't afford a whole new brain.&quot; # An object that holds commands: class Macro: def __init__(self): self.commands = [] def add(self, command): self.commands.append(command) def run(self): for c in self.commands: c.execute() macro = Macro() macro.add(Loony()) macro.add(NewBrain()) macro.add(Afford()) macro.run() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z FlowerVisitors.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c11:FlowerVisitors.py # Demonstration of &quot;visitor&quot; pattern. from __future__ import generators import random # The Flower hierarchy cannot be changed: class Flower(object): def accept(self, visitor): visitor.visit(self) def pollinate(self, pollinator): print self, &quot;pollinated by&quot;, pollinator def eat(self, eater): print self, &quot;eaten by&quot;, eater def __str__(self): return self.__class__.__name__ class Gladiolus(Flower): pass class Runuculus(Flower): pass class Chrysanthemum(Flower): pass class Visitor: def __str__(self): return self.__class__.__name__ class Bug(Visitor): pass class Pollinator(Bug): pass class Predator(Bug): pass # Add the ability to do &quot;Bee&quot; activities: class Bee(Pollinator): def visit(self, flower): flower.pollinate(self) # Add the ability to do &quot;Fly&quot; activities: class Fly(Pollinator): def visit(self, flower): flower.pollinate(self) # Add the ability to do &quot;Worm&quot; activities: class Worm(Predator): def visit(self, flower): flower.eat(self) def flowerGen(n): flwrs = Flower.__subclasses__() for i in range(n): yield random.choice(flwrs)() # It's almost as if I had a method to Perform # various &quot;Bug&quot; operations on all Flowers: bee = Bee() fly = Fly() worm = Worm() for flower in flowerGen(10): flower.accept(bee) flower.accept(fly) flower.accept(worm) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z Games.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c05:Games.py # An example of the Abstract Factory pattern. class Obstacle: def action(self): pass class Player: def interactWith(self, obstacle): pass class Kitty(Player): def interactWith(self, obstacle): print &quot;Kitty has encountered a&quot;, obstacle.action() class KungFuGuy(Player): def interactWith(self, obstacle): print &quot;KungFuGuy now battles a&quot;, obstacle.action() class Puzzle(Obstacle): def action(self): print &quot;Puzzle&quot; class NastyWeapon(Obstacle): def action(self): print &quot;NastyWeapon&quot; # The Abstract Factory: class GameElementFactory: def makePlayer(self): pass def makeObstacle(self): pass # Concrete factories: class KittiesAndPuzzles(GameElementFactory): def makePlayer(self): return Kitty() def makeObstacle(self): return Puzzle() class KillAndDismember(GameElementFactory): def makePlayer(self): return KungFuGuy() def makeObstacle(self): return NastyWeapon() class GameEnvironment: def __init__(self, factory): self.factory = factory self.p = factory.makePlayer() self.ob = factory.makeObstacle() def play(self): self.p.interactWith(self.ob) g1 = GameEnvironment(KittiesAndPuzzles()) g2 = GameEnvironment(KillAndDismember()) g1.play() g2.play() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z Games2.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c05:Games2.py # Simplified Abstract Factory. class Kitty: def interactWith(self, obstacle): print &quot;Kitty has encountered a&quot;, obstacle.action() class KungFuGuy: def interactWith(self, obstacle): print &quot;KungFuGuy now battles a&quot;, obstacle.action() class Puzzle: def action(self): print &quot;Puzzle&quot; class NastyWeapon: def action(self): print &quot;NastyWeapon&quot; # Concrete factories: class KittiesAndPuzzles: def makePlayer(self): return Kitty() def makeObstacle(self): return Puzzle() class KillAndDismember: def makePlayer(self): return KungFuGuy() def makeObstacle(self): return NastyWeapon() class GameEnvironment: def __init__(self, factory): self.factory = factory self.p = factory.makePlayer() self.ob = factory.makeObstacle() def play(self): self.p.interactWith(self.ob) g1 = GameEnvironment(KittiesAndPuzzles()) g2 = GameEnvironment(KillAndDismember()) g1.play() g2.play() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z MouseAction.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c04:mouse:MouseAction.py class MouseAction: def __init__(self, action): self.action = action def __str__(self): return self.action def __cmp__(self, other): return cmp(self.action, other.action) # Necessary when __cmp__ or __eq__ is defined # in order to make this class usable as a # dictionary key: def __hash__(self): return hash(self.action) # Static fields; an enumeration of instances: MouseAction.appears = MouseAction(&quot;mouse appears&quot;) MouseAction.runsAway = MouseAction(&quot;mouse runs away&quot;) MouseAction.enters = MouseAction(&quot;mouse enters trap&quot;) MouseAction.escapes = MouseAction(&quot;mouse escapes&quot;) MouseAction.trapped = MouseAction(&quot;mouse trapped&quot;) MouseAction.removed = MouseAction(&quot;mouse removed&quot;) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z MouseMoves.txt 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/>mouse appears<br/>mouse runs away<br/>mouse appears<br/>mouse enters trap<br/>mouse escapes<br/>mouse appears<br/>mouse enters trap<br/>mouse trapped<br/>mouse removed<br/>mouse appears<br/>mouse runs away<br/>mouse appears<br/>mouse enters trap<br/>mouse trapped<br/>mouse removed<br/><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z MouseTrap2Test.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c04:mousetrap2:MouseTrap2Test.py # A better mousetrap using tables import string, sys sys.path += ['../statemachine', '../mouse'] from State import State from StateMachine import StateMachine from MouseAction import MouseAction class StateT(State): def __init__(self): self.transitions = None def next(self, input): if self.transitions.has_key(input): return self.transitions[input] else: raise &quot;Input not supported for current state&quot; class Waiting(StateT): def run(self): print &quot;Waiting: Broadcasting cheese smell&quot; def next(self, input): # Lazy initialization: if not self.transitions: self.transitions = { MouseAction.appears : MouseTrap.luring } return StateT.next(self, input) class Luring(StateT): def run(self): print &quot;Luring: Presenting Cheese, door open&quot; def next(self, input): # Lazy initialization: if not self.transitions: self.transitions = { MouseAction.enters : MouseTrap.trapping, MouseAction.runsAway : MouseTrap.waiting } return StateT.next(self, input) class Trapping(StateT): def run(self): print &quot;Trapping: Closing door&quot; def next(self, input): # Lazy initialization: if not self.transitions: self.transitions = { MouseAction.escapes : MouseTrap.waiting, MouseAction.trapped : MouseTrap.holding } return StateT.next(self, input) class Holding(StateT): def run(self): print &quot;Holding: Mouse caught&quot; def next(self, input): # Lazy initialization: if not self.transitions: self.transitions = { MouseAction.removed : MouseTrap.waiting } return StateT.next(self, input) class MouseTrap(StateMachine): def __init__(self): # Initial state StateMachine.__init__(self, MouseTrap.waiting) # Static variable initialization: MouseTrap.waiting = Waiting() MouseTrap.luring = Luring() MouseTrap.trapping = Trapping() MouseTrap.holding = Holding() moves = map(string.strip, open(&quot;../mouse/MouseMoves.txt&quot;).readlines()) mouseMoves = map(MouseAction, moves) MouseTrap().runAll(mouseMoves) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z MouseTrapTest.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c04:mousetrap1:MouseTrapTest.py # State Machine pattern using 'if' statements # to determine the next state. import string, sys sys.path += ['../statemachine', '../mouse'] from State import State from StateMachine import StateMachine from MouseAction import MouseAction # A different subclass for each state: class Waiting(State): def run(self): print &quot;Waiting: Broadcasting cheese smell&quot; def next(self, input): if input == MouseAction.appears: return MouseTrap.luring return MouseTrap.waiting class Luring(State): def run(self): print &quot;Luring: Presenting Cheese, door open&quot; def next(self, input): if input == MouseAction.runsAway: return MouseTrap.waiting if input == MouseAction.enters: return MouseTrap.trapping return MouseTrap.luring class Trapping(State): def run(self): print &quot;Trapping: Closing door&quot; def next(self, input): if input == MouseAction.escapes: return MouseTrap.waiting if input == MouseAction.trapped: return MouseTrap.holding return MouseTrap.trapping class Holding(State): def run(self): print &quot;Holding: Mouse caught&quot; def next(self, input): if input == MouseAction.removed: return MouseTrap.waiting return MouseTrap.holding class MouseTrap(StateMachine): def __init__(self): # Initial state StateMachine.__init__(self, MouseTrap.waiting) # Static variable initialization: MouseTrap.waiting = Waiting() MouseTrap.luring = Luring() MouseTrap.trapping = Trapping() MouseTrap.holding = Holding() moves = map(string.strip, open(&quot;../mouse/MouseMoves.txt&quot;).readlines()) MouseTrap().runAll(map(MouseAction, moves)) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z ObservedFlower.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c10:ObservedFlower.py # Demonstration of &quot;observer&quot; pattern. import sys sys.path += ['../util'] from Observer import Observer, Observable class Flower: def __init__(self): self.isOpen = 0 self.openNotifier = Flower.OpenNotifier(self) self.closeNotifier= Flower.CloseNotifier(self) def open(self): # Opens its petals self.isOpen = 1 self.openNotifier.notifyObservers() self.closeNotifier.open() def close(self): # Closes its petals self.isOpen = 0 self.closeNotifier.notifyObservers() self.openNotifier.close() def closing(self): return self.closeNotifier class OpenNotifier(Observable): def __init__(self, outer): Observable.__init__(self) self.outer = outer self.alreadyOpen = 0 def notifyObservers(self): if self.outer.isOpen and \ not self.alreadyOpen: self.setChanged() Observable.notifyObservers(self) self.alreadyOpen = 1 def close(self): self.alreadyOpen = 0 class CloseNotifier(Observable): def __init__(self, outer): Observable.__init__(self) self.outer = outer self.alreadyClosed = 0 def notifyObservers(self): if not self.outer.isOpen and \ not self.alreadyClosed: self.setChanged() Observable.notifyObservers(self) self.alreadyClosed = 1 def open(self): alreadyClosed = 0 class Bee: def __init__(self, name): self.name = name self.openObserver = Bee.OpenObserver(self) self.closeObserver = Bee.CloseObserver(self) # An inner class for observing openings: class OpenObserver(Observer): def __init__(self, outer): self.outer = outer def update(self, observable, arg): print &quot;Bee &quot; + self.outer.name + \ &quot;'s breakfast time!&quot; # Another inner class for closings: class CloseObserver(Observer): def __init__(self, outer): self.outer = outer def update(self, observable, arg): print &quot;Bee &quot; + self.outer.name + \ &quot;'s bed time!&quot; class Hummingbird: def __init__(self, name): self.name = name self.openObserver = \ Hummingbird.OpenObserver(self) self.closeObserver = \ Hummingbird.CloseObserver(self) class OpenObserver(Observer): def __init__(self, outer): self.outer = outer def update(self, observable, arg): print &quot;Hummingbird &quot; + self.outer.name + \ &quot;'s breakfast time!&quot; class CloseObserver(Observer): def __init__(self, outer): self.outer = outer def update(self, observable, arg): print &quot;Hummingbird &quot; + self.outer.name + \ &quot;'s bed time!&quot; f = Flower() ba = Bee(&quot;Eric&quot;) bb = Bee(&quot;Eric 0.5&quot;) ha = Hummingbird(&quot;A&quot;) hb = Hummingbird(&quot;B&quot;) f.openNotifier.addObserver(ha.openObserver) f.openNotifier.addObserver(hb.openObserver) f.openNotifier.addObserver(ba.openObserver) f.openNotifier.addObserver(bb.openObserver) f.closeNotifier.addObserver(ha.closeObserver) f.closeNotifier.addObserver(hb.closeObserver) f.closeNotifier.addObserver(ba.closeObserver) f.closeNotifier.addObserver(bb.closeObserver) # Hummingbird 2 decides to sleep in: f.openNotifier.deleteObserver(hb.openObserver) # A change that interests observers: f.open() f.open() # It's already open, no change. # Bee 1 doesn't want to go to bed: f.closeNotifier.deleteObserver(ba.closeObserver) f.close() f.close() # It's already closed; no change f.openNotifier.deleteObservers() f.open() f.close() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z Observer.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: util:Observer.py # Class support for &quot;observer&quot; pattern. from Synchronization import * class Observer: def update(observable, arg): '''Called when the observed object is modified. You call an Observable object's notifyObservers method to notify all the object's observers of the change.''' pass class Observable(Synchronization): def __init__(self): self.obs = [] self.changed = 0 Synchronization.__init__(self) def addObserver(self, observer): if observer not in self.obs: self.obs.append(observer) def deleteObserver(self, observer): self.obs.remove(observer) def notifyObservers(self, arg = None): '''If 'changed' indicates that this object has changed, notify all its observers, then call clearChanged(). Each observer has its update() called with two arguments: this observable object and the generic 'arg'.''' self.mutex.acquire() try: if not self.changed: return # Make a local copy in case of synchronous # additions of observers: localArray = self.obs[:] self.clearChanged() finally: self.mutex.release() # Updating is not required to be synchronized: for observer in localArray: observer.update(self, arg) def deleteObservers(self): self.obs = [] def setChanged(self): self.changed = 1 def clearChanged(self): self.changed = 0 def hasChanged(self): return self.changed def countObservers(self): return len(self.obs) synchronize(Observable, &quot;addObserver deleteObserver deleteObservers &quot; + &quot;setChanged clearChanged hasChanged &quot; + &quot;countObservers&quot;) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z PaperScissorsRock.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c11:PaperScissorsRock.py # Demonstration of multiple dispatching. from __future__ import generators import random # An enumeration type: class Outcome: def __init__(self, value, name): self.value = value self.name = name def __str__(self): return self.name def __eq__(self, other): return self.value == other.value Outcome.WIN = Outcome(0, &quot;win&quot;) Outcome.LOSE = Outcome(1, &quot;lose&quot;) Outcome.DRAW = Outcome(2, &quot;draw&quot;) class Item(object): def __str__(self): return self.__class__.__name__ class Paper(Item): def compete(self, item): # First dispatch: self was Paper return item.evalPaper(self) def evalPaper(self, item): # Item was Paper, we're in Paper return Outcome.DRAW def evalScissors(self, item): # Item was Scissors, we're in Paper return Outcome.WIN def evalRock(self, item): # Item was Rock, we're in Paper return Outcome.LOSE class Scissors(Item): def compete(self, item): # First dispatch: self was Scissors return item.evalScissors(self) def evalPaper(self, item): # Item was Paper, we're in Scissors return Outcome.LOSE def evalScissors(self, item): # Item was Scissors, we're in Scissors return Outcome.DRAW def evalRock(self, item): # Item was Rock, we're in Scissors return Outcome.WIN class Rock(Item): def compete(self, item): # First dispatch: self was Rock return item.evalRock(self) def evalPaper(self, item): # Item was Paper, we're in Rock return Outcome.WIN def evalScissors(self, item): # Item was Scissors, we're in Rock return Outcome.LOSE def evalRock(self, item): # Item was Rock, we're in Rock return Outcome.DRAW def match(item1, item2): print &quot;%s &lt;--&gt; %s : %s&quot; % ( item1, item2, item1.compete(item2)) # Generate the items: def itemPairGen(n): # Create a list of instances of all Items: Items = Item.__subclasses__() for i in range(n): yield (random.choice(Items)(), random.choice(Items)()) for item1, item2 in itemPairGen(20): match(item1, item2) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z PaperScissorsRock2.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c11:PaperScissorsRock2.py # Multiple dispatching using a table from __future__ import generators import random class Outcome: def __init__(self, value, name): self.value = value self.name = name def __str__(self): return self.name def __eq__(self, other): return self.value == other.value Outcome.WIN = Outcome(0, &quot;win&quot;) Outcome.LOSE = Outcome(1, &quot;lose&quot;) Outcome.DRAW = Outcome(2, &quot;draw&quot;) class Item(object): def compete(self, item): # Use a tuple for table lookup: return outcome[self.__class__, item.__class__] def __str__(self): return self.__class__.__name__ class Paper(Item): pass class Scissors(Item): pass class Rock(Item): pass outcome = { (Paper, Rock): Outcome.WIN, (Paper, Scissors): Outcome.LOSE, (Paper, Paper): Outcome.DRAW, (Scissors, Paper): Outcome.WIN, (Scissors, Rock): Outcome.LOSE, (Scissors, Scissors): Outcome.DRAW, (Rock, Scissors): Outcome.WIN, (Rock, Paper): Outcome.LOSE, (Rock, Rock): Outcome.DRAW, } def match(item1, item2): print &quot;%s &lt;--&gt; %s : %s&quot; % ( item1, item2, item1.compete(item2)) # Generate the items: def itemPairGen(n): # Create a list of instances of all Items: Items = Item.__subclasses__() for i in range(n): yield (random.choice(Items)(), random.choice(Items)()) for item1, item2 in itemPairGen(20): match(item1, item2) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z ShapeFactory1.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c05:shapefact1:ShapeFactory1.py # A simple static factory method. from __future__ import generators import random class Shape(object): # Create based on class name: def factory(type): #return eval(type + &quot;()&quot;) if type == &quot;Circle&quot;: return Circle() if type == &quot;Square&quot;: return Square() assert 1, &quot;Bad shape creation: &quot; + type factory = staticmethod(factory) class Circle(Shape): def draw(self): print &quot;Circle.draw&quot; def erase(self): print &quot;Circle.erase&quot; class Square(Shape): def draw(self): print &quot;Square.draw&quot; def erase(self): print &quot;Square.erase&quot; # Generate shape name strings: def shapeNameGen(n): types = Shape.__subclasses__() for i in range(n): yield random.choice(types).__name__ shapes = \ [ Shape.factory(i) for i in shapeNameGen(7)] for shape in shapes: shape.draw() shape.erase() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z ShapeFactory2.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c05:shapefact2:ShapeFactory2.py # Polymorphic factory methods. from __future__ import generators import random class ShapeFactory: factories = {} def addFactory(id, shapeFactory): ShapeFactory.factories.put[id] = shapeFactory addFactory = staticmethod(addFactory) # A Template Method: def createShape(id): if not ShapeFactory.factories.has_key(id): ShapeFactory.factories[id] = \ eval(id + '.Factory()') return ShapeFactory.factories[id].create() createShape = staticmethod(createShape) class Shape(object): pass class Circle(Shape): def draw(self): print &quot;Circle.draw&quot; def erase(self): print &quot;Circle.erase&quot; class Factory: def create(self): return Circle() class Square(Shape): def draw(self): print &quot;Square.draw&quot; def erase(self): print &quot;Square.erase&quot; class Factory: def create(self): return Square() def shapeNameGen(n): types = Shape.__subclasses__() for i in range(n): yield random.choice(types).__name__ shapes = [ ShapeFactory.createShape(i) for i in shapeNameGen(7)] for shape in shapes: shape.draw() shape.erase() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z State.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c04:statemachine:State.py # A State has an operation, and can be moved # into the next State given an Input: class State: def run(self): assert 1, &quot;run not implemented&quot; def next(self, input): assert 1, &quot;next not implemented&quot; #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z StateDemo.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c04:StateDemo.py # Simple demonstration of the State pattern. class State_d: def __init__(self, imp): self.__implementation = imp def changeImp(self, newImp): self.__implementation = newImp # Delegate calls to the implementation: def __getattr__(self, name): return getattr(self.__implementation, name) class Implementation1: def f(self): print &quot;Fiddle de dum, Fiddle de dee,&quot; def g(self): print &quot;Eric the half a bee.&quot; def h(self): print &quot;Ho ho ho, tee hee hee,&quot; class Implementation2: def f(self): print &quot;We're Knights of the Round Table.&quot; def g(self): print &quot;We dance whene'er we're able.&quot; def h(self): print &quot;We do routines and chorus scenes&quot; def run(b): b.f() b.g() b.h() b.g() b = State_d(Implementation1()) run(b) b.changeImp(Implementation2()) run(b) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z StateMachine.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c04:statemachine:StateMachine.py # Takes a list of Inputs to move from State to # State using a template method. class StateMachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() # Template method: def runAll(self, inputs): for i in inputs: print i self.currentState = self.currentState.next(i) self.currentState.run() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z StrategyPattern.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c06:StrategyPattern.py # The strategy interface: class FindMinima: # Line is a sequence of points: def algorithm(self, line) : pass # The various strategies: class LeastSquares(FindMinima): def algorithm(self, line): return [ 1.1, 2.2 ] # Dummy class NewtonsMethod(FindMinima): def algorithm(self, line): return [ 3.3, 4.4 ] # Dummy class Bisection(FindMinima): def algorithm(self, line): return [ 5.5, 6.6 ] # Dummy class ConjugateGradient(FindMinima): def algorithm(self, line): return [ 3.3, 4.4 ] # Dummy # The &quot;Context&quot; controls the strategy: class MinimaSolver: def __init__(self, strategy): self.strategy = strategy def minima(self, line): return self.strategy.algorithm(line) def changeAlgorithm(self, newAlgorithm): self.strategy = newAlgorithm solver = MinimaSolver(LeastSquares()) line = [ 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 ] print solver.minima(line) solver.changeAlgorithm(Bisection()) print solver.minima(line) #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z Synchronization.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: util:Synchronization.py '''Simple emulation of Java's 'synchronized' keyword, from Peter Norvig.''' import threading def synchronized(method): def f(*args): self = args[0] self.mutex.acquire(); # print method.__name__, 'acquired' try: return apply(method, args) finally: self.mutex.release(); # print method.__name__, 'released' return f def synchronize(klass, names=None): &quot;&quot;&quot;Synchronize methods in the given class. Only synchronize the methods whose names are given, or all methods if names=None.&quot;&quot;&quot; if type(names)==type(''): names = names.split() for (name, val) in klass.__dict__.items(): if callable(val) and name != '__init__' and \ (names == None or name in names): # print &quot;synchronizing&quot;, name klass.__dict__[name] = synchronized(val) # You can create your own self.mutex, or inherit # from this class: class Synchronization: def __init__(self): self.mutex = threading.RLock() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z TestSynchronization.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: util:TestSynchronization.py from Synchronization import * # To use for a method: class C(Synchronization): def __init__(self): Synchronization.__init__(self) self.data = 1 def m(self): self.data += 1 return self.data m = synchronized(m) def f(self): return 47 def g(self): return 'spam' # So m is synchronized, f and g are not. c = C() # On the class level: class D(C): def __init__(self): C.__init__(self) # You must override an un-synchronized method # in order to synchronize it (just like Java): def f(self): C.f(self) # Synchronize every (defined) method in the class: synchronize(D) d = D() d.f() # Synchronized d.g() # Not synchronized d.m() # Synchronized (in the base class) class E(C): def __init__(self): C.__init__(self) def m(self): C.m(self) def g(self): C.g(self) def f(self): C.f(self) # Only synchronizes m and g. Note that m ends up # being doubly-wrapped in synchronization, which # doesn't hurt anything but is inefficient: synchronize(E, 'm g') e = E() e.f() e.g() e.m() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z