Authors: Chetan Giridhar and Rahul Verma

As per wikipedia:

“The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.”

Typically in the Observer Pattern, we would have:

  1. Publisher class that would contain methods for:
    • Registering other objects which would like to receive notifications
    • Notifying any changes that occur in the main object to the registered objects (via registered object’s method)
    • Unregistering objects that do not want to receive any further notifications
  2. Subscriber Class that would contain:
    • A method that is used by the Publisher Class, to notify the objects registered with it, of any change that occurs.
  3. An event that triggers a state change that leads the Publisher to call its notification method

To summarize, Subscriber objects can register and unregister with the Publisher object. So whenever an event, that drives the Publisher’s notification method, occurs, the Publisher notifies the Subscriber objects. The notifications would only be passed to the objects that are registered with the Subject at the time of occurrence of the event.

Read More…