Observer

GoF Definition

Define a one-to-many dependency between objects so that when one object changes

state, all its dependents are notified and updated automatically.

Sometimes you need to notify many objects in the system about something interesting happening in the application. Such a model of sending and receiving notifications is also called a publisher-subscriber model. One or more subscriber objects subscribe to receive notifications from the publisher. And the publisher sends out notifications to all the subscribed objects.

In Observer pattern, there are many observers (objects) that are observing a particular subject (also an object). Observers want to be notified when there is a change made inside the subject. So, they register themselves to that subject. When they lose interest in the subject, they simply unregister from the subject. Using this pattern, an object (subject) can send notifications to multiple observers (a set of objects) at the same time.

The main motivation behind the Observer Pattern is the desire to maintain consistency between related objects without making them tightly coupled.

  • Subject: knows its observers and provides an interface for attaching and detaching Observer objects.

  • Concrete Subject: Stores state of interest to ConcreteObserver and sends a notification to its observers when its state changes

  • Observer: defines an updating interface for objects that should be notified of changes in a subject.

  • Concrete Observer: maintains a reference to a ConcreteSubject object and stores state that should stay consistent with the subject's. It also implements the Observer updating interface to keep its state consistent with the subject's