Observer Pattern

Observer Pattern is a #Design Pattern that could be used to implement #Views utilising the Publish/Subscribe Protocol. It is rather useful at decoupling# the presentations of the data from the data itself. There are two objects in this pattern: subject and observer. Observers don’t need to know each other’s existence, but depends on the subject. When there is a change happen in subject, the subscribed observers need to be notified to synchronise the change. This either done in subject to notify all observers that it keep track of (broadcast), or making it the observer’s responsibility to trigger the update when it is needed (centralised or peer-to-peer).

Note: Subject state should be self-consistent before notification to avoid accessing subject in an inconsistent state. Always making sure that state changing operation is done before the notification.

The Gang of Four advises to use this pattern when:

  • An abstraction has two aspects where one depends on the other.
  • A change to one object changes the other.
  • An object should be able to notify other objects without guessing who they are.

In case 1, we could encapsulate the aspects into two separate objects and apply Observer Pattern. Case 2 wise we can just apply Observer Pattern directly, same with Case 3.

If the updates become too complicated to handle, especially when observer is subscribing to multiple subjects, a change manager class is needed to manage the hassle so in the case when multiple subjects changes, the observer will be notified only once. Such class should be in Mediator Pattern# and Singleton Pattern#. It can be with simple approach or directed-acyclic graphs (DAG) approach. Simple change manager will update all the registered observers of each subject. DAG change manager instead handles the DAG of dependencies between subjects and their observers which is usually preferable if an observer subscribes to multiple subjects as it will update once to observer upon a change of multiple subjects.

Note: Only one change manager is needed for the entire program.

Links to this page
  • Mediator Pattern

    Mediator Pattern could also incorporate #Observer Pattern to implement Publish/Subscribe Protocol as a communication mechanism. Colleagues, implemented as subjects, will notify Mediator, implemented as observer, in an event of interests where the Mediator object calls other colleagues according.

    Unlike #Observer Pattern, Mediator object and its colleagues (clients) know each other. Colleagues class will send and request services from Mediator object in order to interact with other colleague which one may not know about. Mediator object serves the request within its local scope and call the cooperative behaviour by routing requests between the required colleagues. Of course, the Mediator object needs to identify the colleague to search for the appropriate action.

  • Design Pattern
#oop