Friday, March 29, 2019

Observer Pattern

The Observer pattern defines a one to many dependency between objects so that when one object changes state, all of its dependent are notified and updated automatically.

Subject contains a list of observers to notify of any change in its state, so it should provide methods using which observers can register and unregister themselves. Subject also contain a method to notify all the observers of any change and either it can send the update while notifying the observer or it can provide another method to get the update.

Observer should have a method to set the object to watch and another method that will be used by Subject to notify them of any updates.

Category:
Behavioral design pattern

Example:
A good example can be found here.

Associated design principle:
Strive for loosely coupled designs between objects that interact.

Java’s built-in Observer pattern:
The java.util package has an implementation of observer pattern. The package has a Observer interface and Observable class. This is similar to Subject and Observer interface. The drawback here is Observable is a class not interface.

Here is a UML diagram taken from Head First Design pattern to show usage of java’s build-in Observer pattern:


Pros:
  • Provides a loosely coupled design between objects that interact.
    • Subject only knows that observer implement Observer interface. Nothing more.
    • There is no need to modify Subject to add or remove observers.
    • We can reuse subject and observer classes independently of each other.
  • Allows you to send data to many other objects in a very efficient manner.
  • Follows the Open/Closed Principle.

Cons:
  • Subscribers are notified in random order.

References:

No comments:

Post a Comment