Carl Danley

The Observer Pattern

Posted by Carl Danley on .
Featured

The Observer Pattern

Posted by Carl Danley on .

This pattern implements a single object (the subject) that maintains a reference to a collection of objects (known as "observers") and broadcasts notifications when a change to state occurs. When we don't want to observe an object, we simply remove it from the collection of objects being observed. The observer pattern is similar to both the pub/sub implementation and the mediator pattern but still different in purpose & theory and worth mentioning. Study the example below for a good idea of what's happening behind the scenes.

This article is part of a series called JavaScript Design Patterns.

Advantages

  • Requires deeper-level thinking of the relationship between the various components of an application
  • Helps us pinpoint dependencies
  • Excellent at decoupling objects which often promotes smaller, reusable components

Disadvantages

  • Checking the integrity of your application can become difficult
  • Switching a subscriber from one publisher to another can be costly

Example

In the example above, the Subject object becomes a base class from which we build an example stock tracking application. You can see that the StockGrabber object uses the Subject object internally to handle notifications to other components of the application such as the StockUpdaterComponent and the StockChartsComponent.

Additional Resources

Other Common JS Patterns