Design Patterns Observer in Python

Jigisha Sata

9 months 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
			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))

         print ('done')

t = Downloader()


t1 = Worker()

t2 = Worker()

t3 = Worker()
The output of the above code is as follows-
Output for Implementation of the observer pattern
Output for Implementation of the observer pattern
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