Bird
0
0

Given this code snippet, what will be printed when the subject's state changes?

medium📝 Analysis Q4 of 15
LLD - Design — Online Shopping Cart
Given this code snippet, what will be printed when the subject's state changes?
class Subject:
    def __init__(self):
        self.observers = []
    def add_observer(self, obs):
        self.observers.append(obs)
    def notify_observers(self):
        for obs in self.observers:
            obs.update()

class Observer:
    def update(self):
        print('State changed!')

subject = Subject()
observer = Observer()
subject.add_observer(observer)
subject.notify_observers()
AState changed!
BNo output
CError: update method missing
DState changed! State changed!
Step-by-Step Solution
Solution:
  1. Step 1: Analyze observer registration

    The observer instance is added to the subject's observer list correctly.
  2. Step 2: Understand notify_observers behavior

    Calling notify_observers calls update on each observer, which prints 'State changed!'. Only one observer is registered.
  3. Final Answer:

    State changed! -> Option A
  4. Quick Check:

    Notify calls update once = 'State changed!' [OK]
Quick Trick: One observer means one print on notify [OK]
Common Mistakes:
  • Expecting multiple prints without multiple observers
  • Assuming no output without state change method
  • Thinking update method is missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes