Bird
Raised Fist0

Consider this Python code snippet implementing Observer pattern. What will be printed?

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

Consider this Python code snippet implementing Observer pattern. What will be printed?

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

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

s = Subject()
o1 = Observer('A')
o2 = Observer('B')
s.addObserver(o1)
s.addObserver(o2)
s.notify('Hello')
AA received: Hello B received: Hello
BHello Hello
CA received: Hello
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Analyze observer registration

    Two observers named 'A' and 'B' are added to the subject's observer list.
  2. Step 2: Understand notify method

    Notify calls update on each observer, printing their name and message.
  3. Final Answer:

    A received: Hello B received: Hello -> Option A
  4. Quick Check:

    Notify calls update on all observers [OK]
Quick Trick: Notify calls update on all registered observers [OK]
Common Mistakes:
MISTAKES
  • Assuming notify prints message directly
  • Thinking only one observer receives message
  • Ignoring observer names in output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes