|
1 |
| -"""http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia |
2 |
| -
|
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. |
| 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. |
7 | 10 | """
|
8 | 11 | import types
|
9 | 12 |
|
10 | 13 |
|
11 | 14 | class StrategyExample:
|
12 | 15 | def __init__(self, func=None):
|
13 |
| - self.name = 'Strategy Example 0' |
| 16 | + self.name = 'Strategy Example 0' |
14 | 17 | if func is not None:
|
15 |
| - self.execute = types.MethodType(func, self) |
| 18 | + self.execute = types.MethodType(func, self) |
16 | 19 |
|
17 |
| - def execute(self): |
18 |
| - print(self.name) |
| 20 | + def execute(self): |
| 21 | + print(self.name) |
19 | 22 |
|
20 | 23 |
|
21 | 24 | def execute_replacement1(self):
|
22 |
| - print(self.name + ' from execute 1') |
| 25 | + print(self.name + ' from execute 1') |
23 | 26 |
|
24 | 27 |
|
25 | 28 | def execute_replacement2(self):
|
26 |
| - print(self.name + ' from execute 2') |
| 29 | + print(self.name + ' from execute 2') |
27 | 30 |
|
28 | 31 |
|
29 | 32 | if __name__ == '__main__':
|
30 |
| - strat0 = StrategyExample() |
| 33 | + strat0 = StrategyExample() |
31 | 34 |
|
32 | 35 | strat1 = StrategyExample(execute_replacement1)
|
33 |
| - strat1.name = 'Strategy Example 1' |
| 36 | + strat1.name = 'Strategy Example 1' |
34 | 37 |
|
35 | 38 | strat2 = StrategyExample(execute_replacement2)
|
36 | 39 | strat2.name = 'Strategy Example 2'
|
37 | 40 |
|
38 | 41 | strat0.execute()
|
39 |
| - strat1.execute() |
| 42 | + strat1.execute() |
40 | 43 | strat2.execute()
|
0 commit comments