Skip to content
We areTOP 1%

How does the Observer pattern work, and where is it used?

MediumConceptDesign Patterns
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

In the Observer pattern, a subject keeps a list of observers and notifies all of them when its state changes, so observers react without the subject knowing their concrete types. It defines a one-to-many dependency between objects.

  • Structure: the subject exposes subscribe(), unsubscribe() and notify(); each observer implements an update() method.
  • Examples: UI event listeners, a stock price feed updating several displays, and a channel notifying its subscribers about a new video.
  • Push vs pull: the subject can send the changed data with the notification, or observers can query the subject after being notified.
  • Pitfalls: observers that never unsubscribe cause memory leaks, and slow observers delay others unless notification is asynchronous. At system scale, the same idea becomes publish-subscribe messaging.

More in Design Patterns

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account