The Observer pattern is a behavioral pattern where a subject maintains a list of observers and automatically notifies them whenever its state changes. It models a one-to-many dependency so that many objects can react to a single source of truth without being tightly coupled to it.
Key Points: • The subject exposes methods to register and unregister observers, plus a notify step triggered on state change. • Observers implement a common update interface so the subject can notify them generically. • It decouples the subject from the specific logic each observer performs in response to an update. • Common uses include GUI event handling, pub/sub messaging, and real-time data feeds. • Adding a new observer requires no change to the subject's code, only registration.
Example: A weather station (subject) can notify multiple display units (observers) — a phone app, a website widget, and a digital billboard — whenever the temperature changes, without the weather station knowing anything about how each display renders the data.
Interview Tip: A concise interview answer is:
"Observer models a one-to-many relationship where a subject notifies a list of registered observers whenever its state changes, without knowing what each observer does with that update. I'd reach for it any time multiple parts of a system need to react to changes in another object, like UI updates or event-driven notifications."