OOP & Design Patterns - Observer Pattern - Event System, Publish-Subscribe
Given the following thread-safe observer pattern code snippet, what will be the output after the sequence of operations shown below?
import threading
class Observer:
def __init__(self, name):
self.name = name
def update(self, event_type, message):
print(f"{self.name} received {event_type}: {message}")
class Subject:
def __init__(self):
self.lock = threading.Lock()
self.observers = {}
def subscribe(self, observer, event_type):
with self.lock:
if event_type not in self.observers:
self.observers[event_type] = set()
self.observers[event_type].add(observer)
def unsubscribe(self, observer, event_type):
with self.lock:
if event_type in self.observers and observer in self.observers[event_type]:
self.observers[event_type].remove(observer)
if not self.observers[event_type]:
del self.observers[event_type]
def notify(self, event_type, message):
with self.lock:
observers_snapshot = list(self.observers.get(event_type, []))
for observer in observers_snapshot:
observer.update(event_type, message)
subject = Subject()
obs1 = Observer('Obs1')
obs2 = Observer('Obs2')
subject.subscribe(obs1, 'eventA')
subject.subscribe(obs2, 'eventB')
subject.notify('eventA', 'Hello A')
subject.notify('eventB', 'Hello B')
subject.unsubscribe(obs1, 'eventA')
subject.notify('eventA', 'Hello again A')
What is printed?