-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy_and_observer_pattern.py
More file actions
57 lines (42 loc) · 1.16 KB
/
strategy_and_observer_pattern.py
File metadata and controls
57 lines (42 loc) · 1.16 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
# Observer Pattern
class Counter:
def __init__(self):
self._observers = []
self._state = 0
def attach(self, observer):
self._observers.append(observer)
def notify(self):
for observer in self._observers:
observer.update(self._state)
def increment(self):
self._state += 1
self.notify()
class Observer:
def __init__(self, id):
self._id = id
def update(self, state):
print(f"Observer {self._id}: Counter state is now {state}")
# Strategy Pattern
class Printer:
def __init__(self, print_strategy=None):
if print_strategy:
self.print = print_strategy
def print(self, text):
print(text)
def print_uppercase(text):
print(text.upper())
def print_lowercase(text):
print(text.lower())
# Application
counter = Counter()
observers = [Observer(i) for i in range(3)]
for observer in observers:
counter.attach(observer)
printer = Printer()
for i in range(5):
counter.increment()
if i % 2 == 0:
printer = Printer(print_uppercase)
else:
printer = Printer(print_lowercase)
printer.print(f"End of iteration {i}")