strategy.py 1.2 KB

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