Bird
Raised Fist0

What will be the output of this code snippet?

medium📝 Analysis Q5 of Q15
LLD - Behavioral Design Patterns — Part 1

What will be the output of this code snippet?

class Subject:
    def __init__(self):
        self.observers = set()
    def addObserver(self, observer):
        self.observers.add(observer)
    def notify(self, message):
        for obs in self.observers:
            obs.update(message)

class Observer:
    def __init__(self, id):
        self.id = id
    def update(self, message):
        print(f"Observer {self.id}: {message}")

s = Subject()
o1 = Observer(1)
o2 = Observer(2)
s.addObserver(o1)
s.addObserver(o1)
s.addObserver(o2)
s.notify('Update')
AObserver 1: Update Observer 2: Update
BObserver 1: Update Observer 1: Update Observer 2: Update
CObserver 2: Update
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand observer storage

    Observers are stored in a set, which prevents duplicates.
  2. Step 2: Analyze addObserver calls

    Adding o1 twice results in only one instance stored; o2 is added once.
  3. Step 3: Notify calls update on unique observers

    Both observers 1 and 2 receive the update once.
  4. Final Answer:

    Observer 1: Update Observer 2: Update -> Option A
  5. Quick Check:

    Set prevents duplicate observers [OK]
Quick Trick: Sets prevent duplicate observers in registration [OK]
Common Mistakes:
MISTAKES
  • Assuming duplicate observers get notified multiple times
  • Confusing list with set behavior
  • Ignoring observer uniqueness

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes