Reading Time: 1 minutes
Observer Design Pattern in Python
Write a Python program to implement Observer Design Pattern.
class Core: '''Represents what is being observed.''' def __init__(self, name): '''Initialized an empty list of observers; Set the name of the core; initialize its temperature.''' self._observers = [] self._name = name self._temp = 0 def attach(self, observer): '''If the observer is not already in the observers list; append the observer to the list''' if observer not in self._observers: self._observers.append(observer) def detach(self, observer): '''Remove the observer from the list of observers.''' try: self._observers.remove(observer) except ValueError: print("Observer is already not in the list of observers.") def notify(self): '''Alert all observers.''' for observer in self._observers: observer.update(self) # Getter that gets the temperature of core @property def temp(self): '''The @property decorator makes a property object 'temp', on which a setter can be defined, as done below.''' return self._temp #Setter that sets the temperature of core @temp.setter def temp(self, temp): '''Notify the observers whenever somebody changes the core temperature. @temp.setter notation signifies the setter method of the temp property which allows to set the temperature using the assignment operator i.e. objectOfCore.temp = 300 sets the temp attribute to 50''' self._temp = temp self.notify() class FacultyMonitoringCore: '''Observer: Monitoring the subject.''' def update(self, subject): '''Alert method invoked when the notify() method in the subject is invoked.''' if subject._temp > 350: print("FacultyMonitoringCore says: {} has temperature {}. Code Red!!!".format(subject._name, subject._temp)) else: print("FacultyMonitoringCore says: {} has temperature {}. Everything is under control.".format(subject._name, subject._temp)) # Create a subject to be monitored coreOne = Core("Core 1") # Create observers facultyMonitoringCoreOne = FacultyMonitoringCore() facultyMonitoringCoreTwo = FacultyMonitoringCore() # Attach the observers to the subject coreOne.attach(facultyMonitoringCoreOne) coreOne.attach(facultyMonitoringCoreTwo) # Changing the temperature of the core, which invokes the notify() method of class Core, which in turn invokes the update() method of each observer. coreOne.temp = 300 coreOne.temp = 360 ## OUTPUT ## FacultyMonitoringCore says: Core 1 has temperature 300. Everything is under control. FacultyMonitoringCore says: Core 1 has temperature 300. Everything is under control. FacultyMonitoringCore says: Core 1 has temperature 360. Code Red!!! FacultyMonitoringCore says: Core 1 has temperature 360. Code Red!!!