Thursday, March 9, 2023

Observer Pattern in Python...

The observer design pattern is a very popular design pattern in the Object Oriented world. I must admit, I first saw the utilities of this design pattern while studying the document view architecture of the MFC source code.

Later on, I used this pattern in many places.

There is a lot of similarity between the Observer Pattern, the Callback mechanism, and the Event Handler process in Java. Usually, the callback method is used when there is only one observer who awaits the signal from the observee.

So, let me put it in this fashion.

Suppose, there is a central document that is viewed by a few applications - someone is viewing it in a spreadsheet, someone as a Pie chart, and so on.

Now if the data in the document is updated, all the viewers must be updated and they should synchronize their views with the latest data set. So basically all the viewers were observing the central data. The moment it changes, all the observers get their respective views updated.

Here goes the Python code for this observer pattern

from __future__ import annotations

from abc import ABC,abstractmethod

from typing import List

class Subject(ABC):

   @abstractmethod

   def addObserver(self,observer):

       pass

   @abstractmethod

   def removeObserver(self,observer):

       pass

   @abstractmethod

   def notifyObservers(self):

       pass

class ConcreteSubject(Subject):

   _observers = []

   _state = "my current state"

   def addObserver(self,observer):

       self._observers.append(observer)

   def removeObserver(self,observer):

       self._observers.remove(observer)

   def notifyObservers(self):

       for observer in self._observers:

           observer.update()

   def dosomething(self):

       print("I am doing something which will change my state.Notifying observers")

       self._state = "subject state has been changed"

       self.notifyObservers()

class Observer(ABC):

   @abstractmethod

   def update(self):

       pass

class ConcreteObserver(Observer):

   def __init__(self,subject):

       self._subject = subject

   def update(self):

       print(self._subject._state)

if __name__ == '__main__':

   concretesubject = ConcreteSubject()

   observer1 = ConcreteObserver(concretesubject)

   observer2 = ConcreteObserver(concretesubject)

   concretesubject.addObserver(observer1)

   concretesubject.addObserver(observer2)

   concretesubject.dosomething()


For all other inquisitive student communities, here goes my training on Observer Pattern in Java


And for all the Bengali medium students, here we go


Observer Pattern in Bengali...

No comments: