Extension: Observer Pattern

The Observer pattern defines a one-to-many relationship between objects. When one object (the Subject) changes state, all registered Observersare automatically notified. This creates loose coupling — the Subject does not need to know anything specific about its observers.

Real-World Examples

  • Stock ticker app — UI widgets update when prices change
  • Social media notifications — followers notified when you post
  • Event systems in GUI frameworks — button click notifies multiple handlers
  • Spreadsheet cells — changing one cell triggers recalculation in others

Subject and Observer Roles

class StockMarket:         # Subject
    def __init__(self):
        self._observers = []
    def subscribe(self, obs):
        self._observers.append(obs)
    def _notify(self, event):
        for obs in self._observers:
            obs.update(event)  # call each observer
    def set_price(self, stock, price):
        self._notify(f"{stock}: {price}")

Loose Coupling

The Subject only knows about the Observer interface (the update() method). It does not need to know about PriceLogger, EmailAlert, or any other concrete observer. You can add new observer types without changing StockMarket at all.

Your Task

Write class StockMarket: with these methods:

  1. __init__(self): initialise self._observers = []
  2. subscribe(self, observer): append observer to self._observers
  3. unsubscribe(self, observer): remove observer from self._observers
  4. _notify(self, event): call obs.update(event) on every observer
  5. set_price(self, stock, price): call self._notify(f"{stock}: {price}")
Section 1/4Real-World Examples

Real-World Examples

Explore this concept

Extension: Observer Pattern

The Observer pattern defines a one-to-many relationship between objects. When one object (the Subject) changes state, all registered Observersare automatically notified. This creates loose coupling — the Subject does not need to know anything specific about its observers.

Real-World Examples

  • Stock ticker app — UI widgets update when prices change
  • Social media notifications — followers notified when you post
  • Event systems in GUI frameworks — button click notifies multiple handlers
  • Spreadsheet cells — changing one cell triggers recalculation in others

Output:

Click "Check" to run your code.