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:
}
}
}
}
}
}
}
}
subject.
subject.
subject.
subject.
// Output:
// Observer 1 received data: { message: '
// Observer 2 received data: { message: '
// Observer 3 received data: { message: '
subject.
subject.
// 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.