Python Design Patterns - Observer Pattern
In this pattern, objects are represented as observers that wait for an event to trigger. An observer attaches to the subject once the specified event occurs. As the event occurs, the subject tells the observers that it has occurred.
The following UML diagram represents the observer pattern −
Example - How to implement the observer pattern?
Let us now see how to implement the observer pattern.
main.py
import threading
import time
import pdb
class Downloader(threading.Thread):
def run(self):
print('downloading')
for i in range(1,5):
self.i = i
time.sleep(2)
print('unfunf')
return 'hello world'
class Worker(threading.Thread):
def run(self):
for i in range(1,5):
print('worker running: %i (%i)' % (i, t.i))
time.sleep(1)
t.join()
print('done')
t = Downloader()
t.start()
time.sleep(1)
t1 = Worker()
t1.start()
t2 = Worker()
t2.start()
t3 = Worker()
t3.start()
Output
The above program generates the following output −
downloading worker running: 1 (1) worker running: 1 (1) worker running: 1 (1) unfunf done done worker running: 2 (1) worker running: 2 (1) done worker running: 2 (1) done done worker running: 3 (1) worker running: 3 (1) done worker running: 3 (1) done done worker running: 4 (1) worker running: 4 (1) done worker running: 4 (1) done done done
Explanation
The above code explains the procedure of downloading a particular result. As per the observer pattern logic, every object is treated as observer. It prints the output when event is triggered.
Advertisements