Contact Me

Observer

 This pattern allows you to define a one-to-many dependency between objects, such that when one object (the subject) changes state, all of its dependents (the observers) are notified and updated automatically. This can be useful when you want to notify multiple objects about a change in another object, and when you want to abstract the details of how the change is communicated from the objects being notified.


Here is an example of the observer pattern in JavaScript:


class Subject {

constructor() {

  this.observers = [];

}

subscribe(observer) {

  this.observers.push(observer);

}

unsubscribe(observer) {

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

}

notify(data) {

  this.observers.forEach(observer => observer.update(data));

}

}

class Observer {

constructor(name) {

  this.name = name;

}

update(data) {

  console.log(`${this.name} received data:`, data);

}

}

const subject = new Subject();

const observer1 = new Observer('Observer 1');

const observer2 = new Observer('Observer 2');

const observer3 = new Observer('Observer 3');

subject.subscribe(observer1);

subject.subscribe(observer2);

subject.subscribe(observer3);

subject.notify({ message: 'Hello, World!' });

// Output:

// Observer 1 received data: { message: 'Hello, World!' }

// Observer 2 received data: { message: 'Hello, World!' }

// Observer 3 received data: { message: 'Hello, World!' }

subject.unsubscribe(observer2);

subject.notify({ message: 'Hi, there!' });

// Output:

// Observer 1 received data: { message: 'Hi, there!' }

// Observer 3 received data: { message: 'Hi, there!' }


In this example, the Subject class is a class that represents an object that can be observed, and the Observer class is a class that represents an object that observes a subject. The Subject class has a subscribe() method for adding observers, an unsubscribe() method for removing observers, and a notify() method for notifying observers about a change in the subject. The Observer class has an update() method for receiving notifications from the subject.

To use the observer pattern, we create an instance of the Subject class, and then create instances of the Observer class. We register the observer objects with the subject using the subscribe() method, and then use the notify() method of the Subject class to send notifications to the registered observers.

When the notify() method is called, it calls the update() method on each of the registered observers, passing in the data that was passed to the notify() method. This allows the observers to be notified about a change in the subject, and to update their state accordingly.