Observer Pattern

Consider a situation where we have an object that depends upon some event from another object. We can have several ways of implementing this relationship. Two of the most popular approaches are polling based and event based. Polling based approach works best when one object depends upon many others. Even based works better when we have many objects that depend upon one source.

The observer pattern is a more formalized form of the event based, publish-subscribe relationship between objects.

The Observer Pattern has four main participants

  • Subject: The interface or abstract class defining the operations for attaching and de-attaching observers to the subject.
  • ConcreteSubject: The concrete Subject class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
  • Observer: The interface or abstract class defining the operations to be used to notify this object.
  • ConcreteObserver: The concrete Observer implementations.