Observer Pattern in TypeScript
Introduction to the Observer Pattern
Welcome back! We're continuing our exploration of Behavioral Patterns. In this lesson, we will delve into the Observer Pattern, another fundamental pattern that emphasizes object communication and responsibility distribution. This pattern allows an object, known as the subject, to maintain a list of its dependents, called observers, and notify them automatically of any state changes, usually by calling one of their methods.
Previously, we looked at the Command Pattern, which encapsulates a request as an object. Now, let's build on that knowledge and explore how the Observer Pattern facilitates communication between objects in a seamless and efficient manner.
Core Components of the Observer Pattern
Let's break down the process into clear steps to implement the Observer Pattern.
Step 1: Define the Observer
Start by defining the Observer interface, which specifies the contract for receiving updates. In TypeScript, interfaces are commonly used for this purpose, and we can specify the type of the parameter in the update method.
In this code snippet, the Subscriber interface defines the update method, which takes a news string as a parameter. Any class that implements this interface must provide its own implementation of the update method.
Step 2: Create the Subject
Next, create the NewsPublisher class, which acts as the Subject. This class maintains a list of subscribers and provides methods to add and remove subscribers, as well as to notify them. In TypeScript, we add type annotations for the subscribers array and method parameters.
The NewsPublisher class has three methods: addSubscriber to add a new subscriber, removeSubscriber to remove an existing subscriber, and publish to notify all subscribers of new news. All parameters and properties are explicitly typed.
