-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_generic.py
59 lines (40 loc) · 1.61 KB
/
strategy_generic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import abc
class StrategyInterface(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(self, subclass):
return (hasattr(subclass, 'execute_strategy') and
callable(subclass.execute_strategy))
@abc.abstractmethod
def execute_strategy(self, attribute: str) -> str:
raise NotImplementedError
class ConcreteStrategyA():
def execute_strategy(self, attribute: str) -> None:
"""Overrides StrategyInterface.algorithm_interface()"""
print('strategy ', attribute)
class ConcreteStrategyB():
def execute_strategy(self, attribute: str) -> None:
"""Overrides StrategyInterface.algorithm_interface()"""
print('strategy ', attribute)
class ConcreteStrategyC():
def execute_strategy(self, attribute: str) -> None:
"""Overrides StrategyInterface.algorithm_interface()"""
print('strategy ', attribute)
class Context:
def __init__(self):
self.strategy = None
def set_strategy(self, strategy: StrategyInterface):
self.strategy = strategy
def execute(self, attribute: str):
return self.strategy.execute_strategy(attribute)
if __name__ == "__main__":
print(issubclass(ConcreteStrategyA, StrategyInterface))
print(issubclass(ConcreteStrategyB, StrategyInterface))
print(issubclass(ConcreteStrategyC, StrategyInterface))
print(ConcreteStrategyA.__mro__)
context = Context()
context.set_strategy(ConcreteStrategyA())
context.execute('A')
context.set_strategy(ConcreteStrategyB())
context.execute('B')
context.set_strategy(ConcreteStrategyC())
context.execute('C')