Bird
Raised Fist0

Identify the bug in this Observer pattern implementation:

medium📝 Analysis Q14 of Q15
LLD - Design — Chess Game
Identify the bug in this Observer pattern implementation:
class Subject:
    def __init__(self):
        self.observers = set()
    def addObserver(self, obs):
        self.observers.add(obs)
    def notifyObservers(self):
        for obs in self.observers:
            obs.update('Update')

class Observer:
    def update(self, message):
        print(message)

subject = Subject()
obs = Observer()
subject.addObserver(obs)
subject.addObserver(obs)
subject.notifyObservers()
AObservers list should be a list, not a set
BObservers are stored in a set, so duplicates are ignored
CnotifyObservers method is missing parentheses
DObserver class lacks update method
Step-by-Step Solution
Solution:
  1. Step 1: Check data structure for observers

    Observers are stored in a set, which removes duplicates automatically.
  2. Step 2: Understand effect on duplicates

    Adding the same observer twice results in only one notification.
  3. Final Answer:

    Observers are stored in a set, so duplicates are ignored -> Option B
  4. Quick Check:

    Set removes duplicates = single notification [OK]
Quick Trick: Sets ignore duplicates, so repeated observers notify once [OK]
Common Mistakes:
MISTAKES
  • Thinking duplicates cause multiple notifications
  • Confusing set with list behavior
  • Assuming missing method errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes