Observer Design Pattern :)
It is a kind of design pattern which defines one to many relationships between objects and when state of the one object changes, all the dependent objects will be notified and updated automatically.
This is also used to handle distributed event handling system, allowing multiple objects to react to changes to another object without tightly coupling them together.
class observer:
def update(self,message):
pass
class Subject:
def __init__(self):
self._observer = []
def attach(self,observer):
self._observer.append(observer)
def dettach(self,observer):
self._observer.remove(observer)
def notify(self,message):
for observer in self._observer:
observer.update(message)
class ConcreteObserver(observer):
def __init__(self,name):
self._name = name
def update(self,message):
print(f"{self._name} recieved message {message}")
class ConcreteSubject(Subject):
def __init__(self,state):
super().__init__()
self._state = state
def get_state(self):
return self._state
def set_state(self,state):
self._state = state
self.notify(f"changed state to {self._state}")
sub = ConcreteSubject("initial state")
obs1 = ConcreteObserver("observer1")
obs2 = ConcreteObserver("observer2")
sub.attach(obs1)
sub.attach(obs2)
sub.set_state("new state")
In the above code snippets:
领英推荐
The observer class defines an interface for observers with an update method. the subject class represents the subject being observed. it maintains list of observers and provides method to attach, detach and notify them. The concreteobserver class implements observer interface and provides update method to react changes. The concretesubject class extends subject class and contains the state of the observers are interested in. It also notifies observers when the state changes.
When you run the code, you will see both the observers are notified and updated when the subject's state changes.
#oops #designPatterns #ObserverDP