Observer
You'll learn to
- -Explain Observer as subscribe-and-be-told, using a newsletter picture
- -Run a subject with two kinds of subscribers and show that unsubscribing works
- -Describe push versus pull, and the "lapsed listener" memory problem
When you subscribe to a newsletter, the publisher does not know who you are as a person and does not care what you do with the email. It keeps a list of subscribers and, whenever something new is published, sends it to everyone on the list. The Observer pattern is exactly that: one object (the subject) keeps a list of other objects (observers) and tells every one of them whenever its state changes, without knowing anything concrete about them.
The Core Mechanic
In the demo, a stock ticker is the subject. An email alert and a text-message alert (SMS, short message service) are observers. Watch the second block of output: after the text alert unsubscribes, only the email alert is told about the next price.
Now the payoff. Suppose an OrderService calls the email and SMS code directly, and marketing asks for push notifications. Without Observer you must open and edit OrderService. With Observer you write one new observer class and subscribe it. The order code never changes.
Push vs. Pull
In the push version above, the subject sends the data inside the notification, as in update(event). In the pull version, the subject only says "something changed", and each observer asks the subject for whatever it needs. Push is simpler and fits when most observers want the same data. Pull is more flexible when observers care about different parts of the subject's state and you do not want to put everything into every message.
Where Observer Becomes a System's Backbone
A full notification system, which you will design in a later case study, is Observer at the scale of a whole architecture. An event happens (an order shipped, a price dropped), and any number of channels listen for it, without the event code knowing which channels exist. The same idea powers the click handlers behind buttons on a screen, and the publish-subscribe messaging you meet in high-level design (HLD) rounds.
A subtle failure: if an observer is never unsubscribed when it should be, the subject's list still points at it. The object can never be cleaned up (garbage collection, the automatic freeing of memory nothing refers to, skips it), which leaks memory. This is the "lapsed listener" problem. Always give the design an unsubscribe path.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!