Bird
Raised Fist0

Given the following thread-safe observer pattern code snippet, what will be the output after the sequence of operations shown below?

easy🧾 Code Trace Q12 of Q15
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?
AObs1 received eventA: Hello A Obs2 received eventB: Hello B Obs1 received eventA: Hello again A
BObs1 received eventA: Hello A Obs1 received eventA: Hello again A Obs2 received eventB: Hello B
CObs2 received eventB: Hello B Obs1 received eventA: Hello again A
DObs1 received eventA: Hello A Obs2 received eventB: Hello B
Step-by-Step Solution
Solution:
  1. Step 1: Trace subscriptions and notifications

    Obs1 subscribes to 'eventA', Obs2 to 'eventB'. First notify('eventA') calls Obs1.update, printing "Obs1 received eventA: Hello A". Then notify('eventB') calls Obs2.update, printing "Obs2 received eventB: Hello B".
  2. Step 2: Trace unsubscribe and final notification

    Obs1 unsubscribes from 'eventA'. The final notify('eventA') finds no observers, so no output for Obs1. Therefore, the last notification does not print anything.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Unsubscribed observers do not receive notifications [OK]
Quick Trick: Unsubscribed observers do not receive notifications [OK]
Common Mistakes:
MISTAKES
  • Assuming unsubscribed observers still get notified
Trap Explanation:
PITFALL
  • Some think unsubscribe doesn't remove observer immediately, causing extra prints.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to trace thread-safe observer notification and subscription state.
Master "Observer Pattern - Event System, Publish-Subscribe" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes