Design Patterns In TypeScript — Observer
How to define and maintain dependencies between objects
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.
How Does It Work?
Initially, we have an Observable class that contains something that other objects are interested in listening to. It can be its state (a composition of multiple properties) or just a single property. In this class, we will have a public subscribe method and a private publishing method to inform observers that something has changed.
Observers will subscribe to the Observable class change of state, passing a callback function. Then, every time the state changes in this subscription, the observers’ callback will be called with the new value and other information about the event.
First, we’ll define the
Listener type and the
createObserver function. The…