Codacoda
Back to Academy

design patterns

Observer

The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. It is the foundation of event-driven programming. The key participants are the Subject (knows its observers and provides an interface for attaching and detaching Observer objects), ConcreteSubject (stores state of interest and sends notifications when its state changes), Observer (defines an update interface), and ConcreteObserver (maintains a reference to a ConcreteSubject and implements the update interface). Think of a newspaper subscription: subscribers (observers) sign up to receive the paper, and when a new edition (state change) is published, all subscribers are notified automatically. Use Observer when a change to one object requires changing others and you do not know how many objects need to change, or when an object should be able to notify other objects without making assumptions about who those objects are.

Use Cases

  • Event handling systems in UI frameworks
  • Real-time data feeds (stock tickers, live scores)
  • Reactive state management (Redux, MobX, Vue reactivity)
  • Publish-subscribe messaging systems

Visualization

observersSubject+attach()+detach()+notify()<<interface>>Observer+update()ConcreteObserverA+update()ConcreteObserverB+update()
Speed:1x
Observer — Subject maintains a list of observers and notifies them of state changesStep 1 / 8

Implementation

Output

Click "Run Code" to see output...