Design Patterns In TypeScript — Observer

How to define and maintain dependencies between objects

Cesar William Alvarenga
3 min readJun 9, 2021
Photo made with Canva.

Also known as Dependents or Publish-Subscribe, the Observer pattern helps us create decoupled components and modules. It improves the testability, composition, and scalability of our applications. In this post, I’m going to show you some concepts around the Observer pattern, how it works, and a practical example.

What is Observer?

The authors of the book Design Patterns: Elements of Reusable Object-Oriented Software defines Observer Pattern as:

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

We can think of the Observer pattern as a communication channel between two different modules or objects in order to lose the coupling between them. The observable is an object that notifies observers of changes in its state or a specific property.

An observable can have multiple observers, and these observers are likely to be unrelated to each other and receive update notifications from the observable class. This is usually achieved by calling a callback function provided by each observer. This mode is generally used to implement event processing systems.

--

--