registerObserver(observer: Observer): void;
removeObserver(observer: Observer): void;
update(temperature: number): void;
class WeatherStation implements Subject {
private observers: Observer[] = [];
private temperature: number;
setTemperature(temp: number) {
console.log(`WeatherStation: new temperature measurement: ${temp}`);
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);
class 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 {
console.log(`Fan: It's hot here, turning on the fan...`);
console.log(`Fan: It's cool, turning off the fan...`);
const weatherStation = new WeatherStation();
const tempDisplay = new TemperatureDisplay();
weatherStation.registerObserver(tempDisplay);
weatherStation.registerObserver(fan);
weatherStation.setTemperature(30);
weatherStation.setTemperature(20);