Observer Pattern
Some objects are interesting to many others. When a product comes back in stock, the customers waiting for it want an email, the search page wants to stop hiding it, and the analytics team wants a record. When a new bid arrives in an auction, the previous top bidder wants to know they were outbid, and every screen showing the auction wants the new price.
The naive way is for the product or the auction to call all of those things directly. The Observer pattern turns it around: the interesting object keeps a list of listeners and tells each of them "something happened," without knowing who they are or what they will do about it.
📣 In one sentence: let an object (the subject) keep a list of listeners (the observers) that all share one small interface, and call each of them when its state changes, so new reactions can be added without editing the subject.
The Problem It Solves
Here is a stock item in an online store, written the direct way. When its count changes, it reaches out to everything that cares.
class InventoryItem:
def __init__(self, sku: str, count: int) -> None:
self.sku = sku
self.count = count
self.waitlist: list[str] = [] # emails of customers waiting
def set_count(self, new_count: int) -> None:
was_empty = self.count == 0
self.count = new_count
if was_empty and new_count > 0:
for email in self.waitlist:
EmailService().send(email, f"{self.sku} is back in stock")
self.waitlist.clear()
SearchIndex.instance().show(self.sku)
if new_count == 0:
SearchIndex.instance().hide(self.sku)
if new_count < 5:
PurchasingTeam.alert(f"reorder {self.sku}, only {new_count} left")
Analytics.track("stock_changed", self.sku, new_count)
It works, but look at what InventoryItem now depends on.
Every new reaction edits the same method. The marketing team wants a push notification when popular items
restock. That is another line in set_count, in a class that is supposed to be about stock counts. The class
changes for reasons that have nothing to do with inventory, which breaks the single responsibility principle.
It knows too much. The item imports email, search, purchasing and analytics. You can't reuse it in a warehouse tool that has no search index, and a failure in the email service now makes stock updates fail.
It is hard to test. To test "count goes to zero," you need a real or patched EmailService, SearchIndex,
PurchasingTeam and Analytics. The test that should be one line becomes twenty lines of setup.
Nothing can be turned on or off at runtime. A store that doesn't want low-stock alerts would need a flag
inside set_count, and every such flag adds another branch.
⚠️ The smell to look for: a state-changing method that ends with a list of calls to other parts of the system ("then email, then index, then log"), especially when that list keeps growing. That is the cue for Observer.