BehavioralverifiedVerified

Observer

Defines a one-to-many dependency so that when one object changes state, all its dependents are notified and updated automatically.

Coming Soon

errorWhat Problem Does the Observer Pattern Solve?

When one object's state change requires updating an unknown number of other objects, directly coupling the subject to its dependents creates a brittle web of dependencies. Adding or removing dependents requires modifying the subject, and the subject must know too much about its observers to notify them.

check_circleHow the Observer Pattern Works

Define a Subject that maintains a list of Observer interfaces and calls their update method when its state changes. Observers register and deregister themselves at runtime. The subject knows nothing about concrete observers—only that they implement the Observer interface—keeping both sides loosely coupled.

Observer Pattern Architecture

hourglass_empty

Rendering diagram...

Implementation by Language

lightbulb

Observer Pattern in the Real World

Think of a newspaper subscription service. The publisher (subject) doesn't know exactly who its subscribers (observers) are—it just maintains a list. When a new edition is printed, it delivers a copy to every subscriber on the list automatically. Subscribers can cancel at any time without the publisher needing to change anything.

Frequently Asked Questions

helpWhat is the difference between Observer and Pub/Sub?

In Observer, the subject knows about its observers directly and notifies them. In Pub/Sub, publishers and subscribers are decoupled through a message broker or event bus — neither knows about the other. Observer is simpler for in-process use; Pub/Sub scales to distributed systems.

helpHow do I prevent memory leaks with the Observer pattern?

Always unsubscribe observers when they are no longer needed. In JavaScript, use AbortController with addEventListener, or store subscription references and call unsubscribe() in cleanup functions (React's useEffect return, Angular's ngOnDestroy). Weak references can also help prevent leaks.

helpCan I use Observer with async operations?

Yes. The notification can be synchronous (notify all observers before continuing) or asynchronous (emit an event and continue immediately). Async variants are common in Node.js EventEmitter and RxJS. Consider whether observers need to complete before the subject proceeds.

How the Observer Pattern Relates to Other Patterns

The Observer pattern is often used alongside the Mediator to coordinate complex notification chains, and shares the decoupling philosophy of the Strategy pattern. When observers need to undo state changes, combine it with the Memento pattern.