| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 file changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -1,36 +1,40 @@ | |||
| 1 | - """http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia""" | ||
| 1 | + """http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia | ||
| 2 | 2 | ||
| 3 | - import types | ||
| 3 | + In most of other languages Strategy pattern is implemented via creating some base strategy interface/abstract class and | ||
| 4 | + subclassing it with a number of concrete strategies (as we can see at http://en.wikipedia.org/wiki/Strategy_pattern), | ||
| 5 | + however Python supports higher-order functions and allows us to have only one class and inject functions into it's | ||
| 6 | + instances, as shown in this example. | ||
| 7 | + """ | ||
| 8 | + import types | ||
| 4 | 9 | ||
| 5 | 10 | ||
| 6 | 11 | class StrategyExample: | |
| 7 | - | ||
| 8 | - def __init__(self, func=None): | ||
| 9 | - self.name = "Strategy Example 0" | ||
| 10 | - if func: | ||
| 12 | + def __init__(self, func=None): | ||
| 13 | + self.name = 'Strategy Example 0' | ||
| 14 | + if func is not None: | ||
| 11 | 15 | self.execute = types.MethodType(func, self) | |
| 12 | 16 | ||
| 13 | 17 | def execute(self): | |
| 14 | 18 | print(self.name) | |
| 15 | 19 | ||
| 16 | 20 | ||
| 17 | - def executeReplacement1(self): | ||
| 18 | - print(self.name + " from execute 1") | ||
| 21 | + def execute_replacement1(self): | ||
| 22 | + print(self.name + ' from execute 1') | ||
| 19 | 23 | ||
| 20 | 24 | ||
| 21 | - def executeReplacement2(self): | ||
| 22 | - print(self.name + " from execute 2") | ||
| 25 | + def execute_replacement2(self): | ||
| 26 | + print(self.name + ' from execute 2') | ||
| 23 | 27 | ||
| 24 | 28 | ||
| 25 | - if __name__ == "__main__": | ||
| 29 | + if __name__ == '__main__': | ||
| 26 | 30 | strat0 = StrategyExample() | |
| 27 | 31 | ||
| 28 | - strat1 = StrategyExample(executeReplacement1) | ||
| 29 | - strat1.name = "Strategy Example 1" | ||
| 32 | + strat1 = StrategyExample(execute_replacement1) | ||
| 33 | + strat1.name = 'Strategy Example 1' | ||
| 30 | 34 | ||
| 31 | - strat2 = StrategyExample(executeReplacement2) | ||
| 32 | - strat2.name = "Strategy Example 2" | ||
| 35 | + strat2 = StrategyExample(execute_replacement2) | ||
| 36 | + strat2.name = 'Strategy Example 2' | ||
| 33 | 37 | ||
| 34 | - strat0.execute() | ||
| 38 | + strat0.execute() | ||
| 35 | 39 | strat1.execute() | |
| 36 | 40 | strat2.execute() | |
| Back | FazBrowse Home | New Git URL |
0 commit comments