strategy.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern
  2. # -written-in-python-the-sample-in-wikipedia
  3. """
  4. In most of other languages Strategy pattern is implemented via creating some
  5. base strategy interface/abstract class and subclassing it with a number of
  6. concrete strategies (as we can see at
  7. http://en.wikipedia.org/wiki/Strategy_pattern), however Python supports
  8. higher-order functions and allows us to have only one class and inject
  9. functions into it's instances, as shown in this example.
  10. """
  11. import types
  12. class StrategyExample:
  13. def __init__(self, func=None):
  14. self.name = 'Strategy Example 0'
  15. if func is not None:
  16. self.execute = types.MethodType(func, self)
  17. def execute(self):
  18. print(self.name)
  19. def execute_replacement1(self):
  20. print(self.name + ' from execute 1')
  21. def execute_replacement2(self):
  22. print(self.name + ' from execute 2')
  23. if __name__ == '__main__':
  24. strat0 = StrategyExample()
  25. strat1 = StrategyExample(execute_replacement1)
  26. strat1.name = 'Strategy Example 1'
  27. strat2 = StrategyExample(execute_replacement2)
  28. strat2.name = 'Strategy Example 2'
  29. strat0.execute()
  30. strat1.execute()
  31. strat2.execute()
  32. ### OUTPUT ###
  33. # Strategy Example 0
  34. # Strategy Example 1 from execute 1
  35. # Strategy Example 2 from execute 2