Search This Blog

2023/08/30

Observer Design Pattern

// Subject (Observable)
class WeatherStation {
constructor() {
this.temperature = 0;
this.observers = [];
}

addObserver(observer) {
this.observers.push(observer);
}

removeObserver(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}

setTemperature(temperature) {
this.temperature = temperature;
this.notifyObservers();
}

notifyObservers() {
this.observers.forEach(observer => {
observer.update(this.temperature);
});
}
}

// Observer
class Observer {
update(temperature) {}
}

// Concrete Observer
class TemperatureDisplay extends Observer {
update(temperature) {
console.log(`Temperature updated: ${temperature}°C`);
}
}

// Usage
const weatherStation = new WeatherStation();
const temperatureDisplay = new TemperatureDisplay();


weatherStation.addObserver(temperatureDisplay);

weatherStation.setTemperature(25); // Output: Temperature updated: 25°C
weatherStation.setTemperature(30); // Output: Temperature updated: 30°C

No comments:

Post a Comment