Bird
0
0

Given the following pseudo-code implementing a behavioral pattern, what is the output?

medium📝 Analysis Q4 of 15
LLD - Behavioral Design Patterns — Part 1
Given the following pseudo-code implementing a behavioral pattern, what is the output?
class Publisher:
    def __init__(self):
        self.subscribers = []
    def subscribe(self, sub):
        self.subscribers.append(sub)
    def notify(self, msg):
        for sub in self.subscribers:
            sub.update(msg)

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

p = Publisher()
s1 = Subscriber("A")
s2 = Subscriber("B")
p.subscribe(s1)
p.subscribe(s2)
p.notify("Hello")
AHello received A Hello received B
BA received Hello B received Hello
CA and B subscribed to Hello
DNo output because notify is not called
Step-by-Step Solution
Solution:
  1. Step 1: Analyze subscription and notification

    Publisher stores subscribers and calls their update method with the message.
  2. Step 2: Trace notify call output

    Notify calls update on s1 and s2, printing their names with the message.
  3. Final Answer:

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

    Notify calls update on subscribers = printed messages [OK]
Quick Trick: Notify calls update on all subscribers [OK]
Common Mistakes:
MISTAKES
  • Confusing message direction in print
  • Missing notify call
  • Assuming notify prints subscription info

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes