Bird
Raised Fist0

Consider the following Python code implementing a thread-safe observer pattern. What will be printed after executing the sequence of method calls shown below?

easy🧾 Trace Q3 of Q15
OOP & Design Patterns - Observer Pattern - Event System, Publish-Subscribe
Consider the following Python code implementing a thread-safe observer pattern. What will be printed after executing the sequence of method calls shown below?

import threading

class Observer:
    def __init__(self, id):
        self.id = id
    def notify(self, event, data):
        print(f'Observer {self.id} got {event} with {data}')

class EventManager:
    def __init__(self):
        self.lock = threading.Lock()
        self.subscribers = {}
    def subscribe(self, observer, event):
        with self.lock:
            self.subscribers.setdefault(event, set()).add(observer)
    def publish(self, event, data):
        with self.lock:
            observers = list(self.subscribers.get(event, []))
        for obs in observers:
            obs.notify(event, data)

mgr = EventManager()
obs1 = Observer(1)
obs2 = Observer(2)
mgr.subscribe(obs1, 'update')
mgr.subscribe(obs2, 'update')
mgr.publish('update', 'version 1')
mgr.publish('delete', 'file.txt')
ANo output
BObserver 1 got update with version 1 Observer 2 got update with version 1 Observer 1 got delete with file.txt Observer 2 got delete with file.txt
CObserver 1 got delete with file.txt Observer 2 got delete with file.txt
DObserver 1 got update with version 1 Observer 2 got update with version 1
Step-by-Step Solution
Solution:
  1. Step 1: Understand subscriptions

    Observers 1 and 2 subscribe only to the 'update' event.
  2. Step 2: Analyze publish calls

    Publishing 'update' triggers notifications to both observers; publishing 'delete' triggers none since no subscribers exist for 'delete'.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Only subscribed events notify observers [OK]
Quick Trick: Only subscribed events trigger notifications [OK]
Common Mistakes:
MISTAKES
  • Assuming all observers receive all events regardless of subscription
  • Thinking 'delete' event triggers notifications despite no subscribers
Trap Explanation:
PITFALL
  • Assuming all observers get notified regardless of event subscription is incorrect.
Interviewer Note:
CONTEXT
  • Tests understanding of event filtering and thread-safe notification.
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