Bird
0
0

Consider the following code snippet implementing the Observer pattern:

medium📝 Analysis Q13 of 15
LLD - Behavioral Design Patterns — Part 1
Consider the following code snippet implementing the Observer pattern:
class Subject:
    def __init__(self):
        self.observers = []
    def register(self, observer):
        self.observers.append(observer)
    def notify(self, message):
        for obs in self.observers:
            obs.update(message)

class Observer:
    def update(self, message):
        print(f"Received: {message}")

subject = Subject()
obs1 = Observer()
obs2 = Observer()
subject.register(obs1)
subject.register(obs2)
subject.notify("Hello")
What will be the output when subject.notify("Hello") is called?
AReceived: Hello Received: Hello
BHello
CNo output
DError: update method not found
Step-by-Step Solution
Solution:
  1. Step 1: Understand Observer pattern flow

    The Subject keeps a list of observers and calls their update method with the message when notify is called.
  2. Step 2: Trace notify call

    Calling notify("Hello") loops over obs1 and obs2, calling update("Hello") on each, which prints "Received: Hello" twice.
  3. Final Answer:

    Received: Hello Received: Hello -> Option A
  4. Quick Check:

    Observer update called twice = two prints [OK]
Quick Trick: Observer calls update on all registered objects [OK]
Common Mistakes:
MISTAKES
  • Assuming only one observer is notified
  • Expecting notify to print directly
  • Forgetting observers must implement update

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes