Design Patterns Observer in Python

Jigisha Sata

a year ago

Design Patterns Observer In Python
Design Patterns Observer In Python
In this article, we will try to see what is observers and how we can implement it in Python. It is a type of design pattern in python where objects are represented as observers. The observers wait for the event to get triggered. Then its attaches to the subject once the specified event occurs and then the subjects inform the observers that the event has occurred.
The UML diagram represents the observer pattern below–
Flowchart of Design Patterns Observer In Python
Flowchart of Design Patterns Observer In Python
Implementation of the observer pattern?
Till now we have a basic idea about what is observers in python. Now let us try to see how we can implement the observer pattern.
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 output of the above code is as follows-
Output for Implementation of the observer pattern
Output for Implementation of the observer pattern
Explanation
Here, in this code, it shows us the procedure of downloading a particular result. Here every object is treated as observer and prints the output when the event gets triggered as per the observer’s pattern logic.
I hope you enjoyed reading this article and finally, you came to know about Design Patterns Observer in Python.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review

We're Online!

Chat now for any query