Observer Pattern in Node.js

The Observer Pattern is a fundamental design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It’s especially useful in situations where you need to maintain consistency between related objects without making them tightly coupled.

In Node.js, the Observer Pattern is commonly implemented using the EventEmitter class from the events module. Here’s a simple example that demonstrates how the Observer Pattern can be used in a Node.js application:

Step 1: Import the EventEmitter

First, you need to import the EventEmitter class from the events module:

javascriptCopy codeconst EventEmitter = require('events');

Step 2: Create the Subject

The subject is the entity that holds the state and notifies observers about changes. In this example, we’ll create a simple TemperatureSensor class that emits an event when the temperature changes:

class TemperatureSensor extends EventEmitter {
constructor() {
super();
this.temperature = 0;
}
setTemperature(newTemp) {
this.temperature = newTemp;
this.emit('temperatureChanged', newTemp);
}
}

Step 3: Create Observers

Observers are entities that want to be notified when the subject’s state changes. In this example, we’ll create two observer functions that will act on temperature changes:

function alertSystem(temp) {
if(temp > 30) {
console.log(Alert! The temperature is too high: ${temp}°C);
}
}
function temperatureLogger(temp) {
console.log(Temperature logged: ${temp}°C);
}

Step 4: Wiring Them Together

Finally, you need to instantiate the subject and register the observers to listen for the temperatureChanged event:

const sensor = new TemperatureSensor();
// Register observers
sensor.on('temperatureChanged', alertSystem);
sensor.on('temperatureChanged', temperatureLogger);
// Simulate temperature change
sensor.setTemperature(25); // Temperature logged: 25°C
sensor.setTemperature(35); // Alert! The temperature is too high: 35°C
// Temperature logged: 35°C

In this setup, sensor is the subject that notifies its observers (alertSystem and temperatureLogger) about the temperature change. The on method is used to subscribe the observers to the temperatureChanged event. When setTemperature is called on the sensor, it updates its state and emits a temperatureChanged event, which in turn notifies all registered observers by invoking their callback functions.

This example demonstrates the core idea of the Observer Pattern: enabling one-to-many dependency relationships between objects so that when one object changes state, all its dependents are notified and updated automatically.