Observer
Last updated
Last updated
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
The Observer pattern is a behavioral design pattern where an object, known as the subject, maintains a list of dependents, called observers, and notifies them of any changes in state, usually by calling one of their methods.
This pattern is commonly used to implement distributed event handling systems.
In JavaScript, you can implement the Observer pattern using plain JavaScript or libraries/frameworks like RxJS or even built-in features like addEventListener
.
In this example:
NewsAgency
is the subject (or observable) that holds news and manages subscribers.
NewsSubscriber
is the observer that receives news updates.
subscribe
, unsubscribe
, and notify
methods are used by the subject to manage subscribers and notify them of changes.
When news is added using addNews
, it triggers the notify
method, which informs all subscribers about the latest news.
Observers (NewsSubscriber
) implement the update
method, which is called by the subject when there are updates.
This demonstrates how the Observer pattern allows for decoupling between subjects and observers, enabling a flexible notification system.