The Observer Pattern

This pattern comes under Behavioural Patterns category.

Also known as Publish-Subscribe Pattern or Dependents Pattern.

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

When to use this pattern:

  • When an abstraction has two aspects, one dependent on the other, Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  • When a change to one object requires changing others, and you don’t know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t want these objects tightly coupled.

Participents:

Subject , ConcreteSubject , Observer, ConcreteObserver.

How it works:

The  terminology used for different objects  in this pattern are Subject(Publisher) and Observers(Subscribers).

The Subject is the object who notifies that the change has occured.The Observers are objects  who change their state according the change.

All observers are notified whenever the subject undergoes a change in state.Each observer will query the subject to synchronize its state with the subject’s state.

The Subject notifies its change without even knowing how many dependents(observers) it has and who its observers are.

Any number of observers can subscribe to this subject to receive notifications

Please note that the above pic. is taken from GOF Design Patterns site.

Prons and Cons:

  • Abstract(loose) coupling between Subject and Observer
  • Support for broadcast communication
  • Unexpected updates may cause serious inconsistancy

Note:

Please go through java.util.Observable and java.util.Observer , if you are interested.

Follow

Get every new post delivered to your Inbox.