-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-event-observer-pattern.py
More file actions
328 lines (226 loc) · 9.13 KB
/
01-event-observer-pattern.py
File metadata and controls
328 lines (226 loc) · 9.13 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""Question: Define a class Event that uses the observer pattern to notify
multiple listeners when an event occurs. Implement methods to add and remove listeners.
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about what classes and methods you need
# - Start with a simple implementation
# - Test your code step by step
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - How do you store multiple listeners/observers?
# - What data structure is best for adding and removing listeners?
# - How do you notify all listeners when an event occurs?
# - What parameters should the notify method accept?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Define the Event class
# ===============================================================================
# Explanation:
# Let's start by creating our Event class. This class will implement the observer
# pattern, allowing multiple listeners to be notified when events occur.
class Event:
pass # We'll add methods next
# What we accomplished in this step:
# - Created the basic Event class structure
# Step 2: Add the constructor
# ===============================================================================
# Explanation:
# The constructor should initialize a list to store all the listeners that
# want to be notified when events occur.
class Event:
def __init__(self):
self._listeners = []
# What we accomplished in this step:
# - Added constructor that initializes an empty listeners list
# - Used underscore prefix to indicate internal/private attribute
# Step 3: Add the add_listener method
# ===============================================================================
# Explanation:
# This method allows new listeners (functions or callable objects) to subscribe
# to the event. They will be called when the event is triggered.
class Event:
def __init__(self):
self._listeners = []
def add_listener(self, listener):
self._listeners.append(listener)
# What we accomplished in this step:
# - Added method to register new listeners
# - Listeners are stored in the internal list
# Step 4: Add the remove_listener method
# ===============================================================================
# Explanation:
# This method allows listeners to unsubscribe from the event.
# They will no longer be notified when the event occurs.
class Event:
def __init__(self):
self._listeners = []
def add_listener(self, listener):
self._listeners.append(listener)
def remove_listener(self, listener):
self._listeners.remove(listener)
# What we accomplished in this step:
# - Added method to unregister listeners
# - Uses list.remove() to find and remove the listener
# Step 5: Add the notify method
# ===============================================================================
# Explanation:
# This method triggers the event by calling all registered listeners.
# It accepts any arguments and passes them to each listener.
class Event:
def __init__(self):
self._listeners = []
def add_listener(self, listener):
self._listeners.append(listener)
def remove_listener(self, listener):
self._listeners.remove(listener)
def notify(self, *args, **kwargs):
for listener in self._listeners:
listener(*args, **kwargs)
# What we accomplished in this step:
# - Added notify method that calls all listeners
# - Uses *args and **kwargs to pass any arguments to listeners
# - Iterates through all listeners and calls each one
# Step 6: Test our Event class
# ===============================================================================
# Explanation:
# Now let's test our Event class by creating listeners and demonstrating
# how the observer pattern works in practice.
class Event:
def __init__(self):
self._listeners = []
def add_listener(self, listener):
self._listeners.append(listener)
def remove_listener(self, listener):
self._listeners.remove(listener)
def notify(self, *args, **kwargs):
for listener in self._listeners:
listener(*args, **kwargs)
# Test our Event class:
def listener1(event_data):
print(f"Listener 1 received: {event_data}")
def listener2(event_data):
print(f"Listener 2 received: {event_data}")
def listener3(event_data):
print(f"Listener 3 received: {event_data}")
print("=== Testing Event with Multiple Listeners ===")
event = Event()
# Add listeners
event.add_listener(listener1)
event.add_listener(listener2)
event.add_listener(listener3)
# Trigger event
print("Triggering event with 'Hello World':")
event.notify("Hello World")
print("\nRemoving listener2 and triggering again:")
event.remove_listener(listener2)
event.notify("Second event")
# What we accomplished in this step:
# - Created multiple listener functions
# - Tested adding and removing listeners
# - Verified that all listeners receive notifications
# - Demonstrated listener removal functionality
# Step 7: Enhanced version with error handling and features
# ===============================================================================
# Explanation:
# Let's create an enhanced version that handles edge cases and provides
# additional features like listener counting and safe removal.
class Event:
def __init__(self, name="Unnamed Event"):
self._listeners = []
self.name = name
def add_listener(self, listener):
if not callable(listener):
raise TypeError("Listener must be callable")
if listener not in self._listeners:
self._listeners.append(listener)
print(f"Added listener to {self.name}")
else:
print(f"Listener already registered for {self.name}")
def remove_listener(self, listener):
try:
self._listeners.remove(listener)
print(f"Removed listener from {self.name}")
except ValueError:
print(f"Listener not found in {self.name}")
def notify(self, *args, **kwargs):
print(f"Notifying {len(self._listeners)} listeners for {self.name}")
for listener in self._listeners:
try:
listener(*args, **kwargs)
except Exception as e:
print(f"Error in listener: {e}")
def get_listener_count(self):
return len(self._listeners)
def clear_listeners(self):
count = len(self._listeners)
self._listeners.clear()
print(f"Cleared {count} listeners from {self.name}")
# Test enhanced version:
print("\n=== Enhanced Event with Error Handling ===")
def good_listener(data):
print(f"Good listener: {data}")
def bad_listener(data):
raise Exception("Something went wrong!")
enhanced_event = Event("User Login Event")
# Test enhanced features
enhanced_event.add_listener(good_listener)
enhanced_event.add_listener(bad_listener)
enhanced_event.add_listener(good_listener) # Try to add duplicate
print(f"Listener count: {enhanced_event.get_listener_count()}")
# Test notification with error handling
enhanced_event.notify("User logged in")
# Test safe removal
enhanced_event.remove_listener(bad_listener)
enhanced_event.remove_listener(bad_listener) # Try to remove again
# Test clearing all listeners
enhanced_event.clear_listeners()
# What we accomplished in this step:
# - Added error handling for invalid listeners
# - Prevented duplicate listener registration
# - Added safe removal with error handling
# - Provided listener counting and clearing functionality
# - Added event naming for better debugging
# ===============================================================================
# CONGRATULATIONS!
#
# You've successfully completed the step-by-step solution!
#
# Key concepts learned:
# - Implementing the observer pattern
# - Managing collections of callback functions
# - Using *args and **kwargs for flexible function calls
# - Error handling in event systems
# - Preventing duplicate registrations
#
# Try it yourself:
# 1. Start with Step 1 and code along
# 2. Test each step before moving to the next
# 3. Understand WHY each step is necessary
# 4. Experiment with modifications (try adding priority levels for listeners!)
#
# Remember: The best way to learn is by doing!
# ===============================================================================