Watchful Eyes, Timely Updates, A Symphony of Awareness
In essence, the Observer Design Pattern transforms your code into a buzzing newsroom, where objects stay tuned for the latest updates, reacting with agility and awareness to any changes in their surroundings. This promotes decoupled communication, efficient updates, and a dynamic ecosystem of informed objects.
from abc import ABC, abstractmethod
class PostSubject(ABC):
@abstractmethod
def register_observer(self, observer):
pass
@abstractmethod
def remove_observer(self, observer):
pass
@abstractmethod
def notify_observers(self):
pass
class Observer(ABC):
@abstractmethod
def update(self, subject, *args, **kwargs):
pass
class BlogPost(PostSubject):
def __init__(self, title, author):
self.title = title
self.author = author
self.readers = []
def register_observer(self, reader):
self.readers.append(reader)
def remove_observer(self, reader):
self.readers.remove(reader)
def notify_observers(self):
for reader in self.readers:
reader.update(self)
def publish(self):
print(f"Author '{self.author}' published a new post: '{self.title}'")
self.notify_observers()
class AuthorDashboard(Observer):
def update(self, subject):
print("Author dashboard: Your post has been published!")
class ReaderNotification(Observer):
def update(self, subject):
print(f"Reader notification: New post by '{subject.author}': '{subject.title}'")