Bird
Raised Fist0

What is wrong with this observer pattern implementation?

medium📝 Analysis Q7 of Q15
LLD - Design — Online Shopping Cart
What is wrong with this observer pattern implementation?
class Subject:
    def __init__(self):
        self.observers = []
    def add_observer(self, observer):
        self.observers.append(observer)
    def notify_observers(self):
        for obs in self.observers:
            obs.update()
        self.observers.clear()
Anotify_observers should not call update on observers.
BObservers list should be cleared before notification.
CClearing observers after notification removes all subscribers permanently.
Dadd_observer should not append observers.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze observer clearing behavior

    Clearing the observers list after notifying removes all observers, so no future notifications occur.
  2. Step 2: Understand impact on subscription

    This breaks the observer pattern because observers must stay subscribed until explicitly removed.
  3. Final Answer:

    Clearing observers after notification removes all subscribers permanently. -> Option C
  4. Quick Check:

    Clearing observers breaks subscription [OK]
Quick Trick: Do not clear observers list after notify [OK]
Common Mistakes:
MISTAKES
  • Clearing observers before notify
  • Thinking notify should not call update
  • Believing add_observer should not append

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes