Observer Pattern
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.
When to Use:
Use the Observer pattern when an object needs to notify other objects without making assumptions about who those objects are.
Example
// Subject Interfaceinterface Subject { registerObserver(observer: Observer): void; removeObserver(observer: Observer): void; notifyObservers(): void;}
// Observer Interfaceinterface Observer { update(temperature: number): void;}
// Concrete Subjectclass WeatherStation implements Subject { private observers: Observer[] = []; private temperature: number;
setTemperature(temp: number) { console.log(`WeatherStation: new temperature measurement: ${temp}`); this.temperature = temp; this.notifyObservers(); }
registerObserver(observer: Observer): void { this.observers.push(observer); }
removeObserver(observer: Observer): void { this.observers = this.observers.filter(obs => obs !== observer); }
notifyObservers(): void { for (const observer of this.observers) { observer.update(this.temperature); } }}
// Concrete Observersclass TemperatureDisplay implements Observer { update(temperature: number): void { console.log(`TemperatureDisplay: I need to update my display with the new temperature: ${temperature}`); }}
class Fan implements Observer { update(temperature: number): void { if (temperature > 25) { console.log(`Fan: It's hot here, turning on the fan...`); } else { console.log(`Fan: It's cool, turning off the fan...`); } }}
// Usageconst weatherStation = new WeatherStation();const tempDisplay = new TemperatureDisplay();const fan = new Fan();
weatherStation.registerObserver(tempDisplay);weatherStation.registerObserver(fan);
weatherStation.setTemperature(30);weatherStation.setTemperature(20);
Pros:
- Loose coupling between subject and observers.
- Flexible and easy to add or remove observers.
Cons:
- Can lead to memory leaks if observers are not properly removed.
- Sometimes difficult to predict the order in which notifications are received.