-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy_final.py
More file actions
executable file
·40 lines (30 loc) · 1.17 KB
/
strategy_final.py
File metadata and controls
executable file
·40 lines (30 loc) · 1.17 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
import types #Import the types module
class Strategy:
"""The Strategy Pattern class"""
def __init__(self, function=None):
self.name = "Default Strategy"
#If a reference to a function is provided, replace the execute() method with the given function
if function:
self.execute = types.MethodType(function, self)
def execute(self): #This gets replaced by another version if another strategy is provided.
"""The defaut method that prints the name of the strategy being used"""
print("{} is used!".format(self.name))
#Replacement method 1
def strategy_one(self):
print("{} is used to execute method 1".format(self.name))
#Replacement method 2
def strategy_two(self):
print("{} is used to execute method 2".format(self.name))
#Let's create our default strategy
s0 = Strategy()
#Let's execute our default strategy
s0.execute()
#Let's create the first varition of our default strategy by providing a new behavior
s1 = Strategy(strategy_one)
#Let's set its name
s1.name = "Strategy One"
#Let's execute the strategy
s1.execute()
s2 = Strategy(strategy_two)
s2.name = "Strategy Two"
s2.execute()