-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy_pattern.py
More file actions
110 lines (65 loc) · 1.96 KB
/
strategy_pattern.py
File metadata and controls
110 lines (65 loc) · 1.96 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
from abc import ABC, abstractmethod
class WeaponBehavior(ABC):
@abstractmethod
def use_weapon(self):
raise NotImplementedError
class Character(ABC):
weapon: WeaponBehavior = None
def set_weapon(self, new_weapon: WeaponBehavior):
self.weapon = new_weapon
@abstractmethod
def fight(self):
pass
def display_character_name(self):
print("This is base character")
class King(Character):
def __init__(self):
self.weapon = KnifeBehavior()
def fight(self):
self.weapon.use_weapon()
class Queen(Character):
def __init__(self):
self.weapon = BowAndArrowBehavior()
def fight(self):
self.weapon.use_weapon()
class KnifeBehavior(WeaponBehavior):
def use_weapon(self):
print("I use knife")
class BowAndArrowBehavior(WeaponBehavior):
def use_weapon(self):
print("I use bow and arrow")
king = King()
queen = Queen()
king.fight()
queen.fight()
king.set_weapon(BowAndArrowBehavior())
king.fight()
class Strategy(ABC):
@abstractmethod
def do_algorithm(self, data: list[str]):
raise NotImplementedError
class Context:
def __init__(self, strategy: Strategy):
self._strategy = strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy: Strategy):
self._strategy = strategy
def do_some_business_logic(self):
text_data = ["a", "b", "c"]
result = self.strategy.do_algorithm(text_data)
print(",".join(result))
class ConcreateStrategyA(Strategy):
def do_algorithm(self, data: list[str]):
return sorted(data)
class ConcreteStrategyB(Strategy):
def do_algorithm(self, data: list[str]):
return reversed(data)
strategy_a = ConcreateStrategyA()
strategy_b = ConcreteStrategyB()
context = Context(strategy_a)
context.do_some_business_logic()
context.strategy = strategy_b
context.do_some_business_logic()