Observer Pattern

With the observer pattern, we have:

  1. An observable object, which can be observed by subscribers in order to notify them.
  2. Subscribers, which can subscribe to and get notified by the observable object.

For example, we can add the logger as a subscriber to the observable.

When the notify method is invoked on the observable, all subscribers get invoked and (optionally) pass the data from the notifier to them.

Observer Pattern The observers listen to events from the subject and are notfied whenever an event occurs. They can then process it accordingly.

Tradeoffs

  • Separation of Concerns: The observer objects aren't tightly coupled to the observable object, and can be (de)coupled at any time. The observable object is responsible for monitoring the events, while the observers simply handle the received data.
  • Decreased performance: Notifying all subscribers might take a significant amount of time if the observer handling becomes too complex, or if there are too many subscibers to notify.

Backlinks