#!/usr/bin/python #coding:utf8 ''' Abstract Factory ''' import random classPetShop: """A pet shop""" def__init__(self, animal_factory=None): """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory defshow_pet(self): """Creates and shows a pet using the abstract factory""" pet = self.pet_factory.get_pet() print("This is a lovely", str(pet)) print("It says", pet.speak()) print("It eats", self.pet_factory.get_food()) # Stuff that our factory makes classDog: defspeak(self): return"woof" def__str__(self): return"Dog" classCat: defspeak(self): return"meow" def__str__(self): return"Cat" # Factory classes classDogFactory: defget_pet(self): return Dog() defget_food(self): return"dog food" classCatFactory: defget_pet(self): return Cat() defget_food(self): return"cat food" # Create the proper family defget_factory(): """Let's be dynamic!""" return random.choice([DogFactory, CatFactory])() # Show pets with various factories if __name__ == "__main__": shop = PetShop() for i inrange(3): shop.pet_factory = get_factory() shop.show_pet() print("=" * 20)
#!/usr/bin/python #coding:utf8 ''' Interpreter ''' classContext: def__init__(self): self.input="" self.output="" classAbstractExpression: defInterpret(self,context): pass classExpression(AbstractExpression): defInterpret(self,context): print"terminal interpret" classNonterminalExpression(AbstractExpression): defInterpret(self,context): print"Nonterminal interpret" if __name__ == "__main__": context= "" c = [] c = c + [Expression()] c = c + [NonterminalExpression()] c = c + [Expression()] c = c + [Expression()] for a in c: a.Interpret(context)
#!/usr/bin/python #coding:utf8 ''' Template Method ''' ingredients = "spam eggs apple" line = '-' * 10 # Skeletons defiter_elements(getter, action): """Template skeleton that iterates items""" for element in getter(): action(element) print(line) defrev_elements(getter, action): """Template skeleton that iterates items in reverse order""" for element in getter()[::-1]: action(element) print(line) # Getters defget_list(): return ingredients.split() defget_lists(): return [list(x) for x in ingredients.split()] # Actions defprint_item(item): print(item) defreverse_item(item): print(item[::-1]) # Makes templates defmake_template(skeleton, getter, action): """Instantiate a template method with getter and action""" deftemplate(): skeleton(getter, action) return template # Create our template functions templates = [make_template(s, g, a) for g in (get_list, get_lists) for a in (print_item, reverse_item) for s in (iter_elements, rev_elements)] # Execute them for template in templates: template()
#!/usr/bin/python #coding:utf8 """ Command """ import os classMoveFileCommand(object): def__init__(self, src, dest): self.src = src self.dest = dest defexecute(self): self() def__call__(self): print('renaming {} to {}'.format(self.src, self.dest)) os.rename(self.src, self.dest) defundo(self): print('renaming {} to {}'.format(self.dest, self.src)) os.rename(self.dest, self.src) if __name__ == "__main__": command_stack = [] # commands are just pushed into the command stack command_stack.append(MoveFileCommand('foo.txt', 'bar.txt')) command_stack.append(MoveFileCommand('bar.txt', 'baz.txt')) # they can be executed later on for cmd in command_stack: cmd.execute() # and can also be undone at will for cmd inreversed(command_stack): cmd.undo()
#!/usr/bin/python #coding:utf8 ''' Interator ''' defcount_to(count): """Counts by word numbers, up to a maximum of five""" numbers = ["one", "two", "three", "four", "five"] # enumerate() returns a tuple containing a count (from start which # defaults to 0) and the values obtained from iterating over sequence for pos, number inzip(range(count), numbers): yield number # Test the generator count_to_two = lambda: count_to(2) count_to_five = lambda: count_to(5) print('Counting to two...') for number in count_to_two(): print number print" " print('Counting to five...') for number in count_to_five(): print number print" "
#!/usr/bin/python #coding:utf8 ''' Mediator ''' """http://dpip.testingperspective.com/?p=28""" import time classTC: def__init__(self): self._tm = tm self._bProblem = 0 defsetup(self): print("Setting up the Test") time.sleep(1) self._tm.prepareReporting() defexecute(self): ifnot self._bProblem: print("Executing the test") time.sleep(1) else: print("Problem in setup. Test not executed.") deftearDown(self): ifnot self._bProblem: print("Tearing down") time.sleep(1) self._tm.publishReport() else: print("Test not executed. No tear down required.") defsetTM(self, TM): self._tm = tm defsetProblem(self, value): self._bProblem = value classReporter: def__init__(self): self._tm = None defprepare(self): print("Reporter Class is preparing to report the results") time.sleep(1) defreport(self): print("Reporting the results of Test") time.sleep(1) defsetTM(self, TM): self._tm = tm classDB: def__init__(self): self._tm = None definsert(self): print("Inserting the execution begin status in the Database") time.sleep(1) #Following code is to simulate a communication from DB to TC import random if random.randrange(1, 4) == 3: return -1 defupdate(self): print("Updating the test results in Database") time.sleep(1) defsetTM(self, TM): self._tm = tm classTestManager: def__init__(self): self._reporter = None self._db = None self._tc = None defprepareReporting(self): rvalue = self._db.insert() if rvalue == -1: self._tc.setProblem(1) self._reporter.prepare() defsetReporter(self, reporter): self._reporter = reporter defsetDB(self, db): self._db = db defpublishReport(self): self._db.update() rvalue = self._reporter.report() defsetTC(self, tc): self._tc = tc if __name__ == '__main__': reporter = Reporter() db = DB() tm = TestManager() tm.setReporter(reporter) tm.setDB(db) reporter.setTM(tm) db.setTM(tm) # For simplification we are looping on the same test. # Practically, it could be about various unique test classes and their # objects while (True): tc = TC() tc.setTM(tm) tm.setTC(tc) tc.setup() tc.execute() tc.tearDown()
#!/usr/bin/python #coding:utf8 ''' State ''' classState(object): """Base state. This is to share functionality""" defscan(self): """Scan the dial to the next station""" self.pos += 1 if self.pos == len(self.stations): self.pos = 0 print("Scanning... Station is", self.stations[self.pos], self.name) classAmState(State): def__init__(self, radio): self.radio = radio self.stations = ["1250", "1380", "1510"] self.pos = 0 self.name = "AM" deftoggle_amfm(self): print("Switching to FM") self.radio.state = self.radio.fmstate classFmState(State): def__init__(self, radio): self.radio = radio self.stations = ["81.3", "89.1", "103.9"] self.pos = 0 self.name = "FM" deftoggle_amfm(self): print("Switching to AM") self.radio.state = self.radio.amstate classRadio(object): """A radio. It has a scan button, and an AM/FM toggle switch.""" def__init__(self): """We have an AM state and an FM state""" self.amstate = AmState(self) self.fmstate = FmState(self) self.state = self.amstate deftoggle_amfm(self): self.state.toggle_amfm() defscan(self): self.state.scan() # Test our radio out if __name__ == '__main__': radio = Radio() actions = [radio.scan] * 2 + [radio.toggle_amfm] + [radio.scan] * 2 actions = actions * 2 for action in actions: action()
#!/usr/bin/python #coding:utf8 """ Strategy In most of other languages Strategy pattern is implemented via creating some base strategy interface/abstract class and subclassing it with a number of concrete strategies (as we can see at http://en.wikipedia.org/wiki/Strategy_pattern), however Python supports higher-order functions and allows us to have only one class and inject functions into it's instances, as shown in this example. """ import types classStrategyExample: def__init__(self, func=None): self.name = 'Strategy Example 0' if func isnotNone: self.execute = types.MethodType(func, self) defexecute(self): print(self.name) defexecute_replacement1(self): print(self.name + ' from execute 1') defexecute_replacement2(self): print(self.name + ' from execute 2') if __name__ == '__main__': strat0 = StrategyExample() strat1 = StrategyExample(execute_replacement1) strat1.name = 'Strategy Example 1' strat2 = StrategyExample(execute_replacement2) strat2.name = 'Strategy Example 2' strat0.execute() strat1.execute() strat2.execute()