Observer Design Pattern

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

In this pattern, we call the publisher the SUBJECT and the subscribers the OBSERVER

Strive for loosely coupled designs between objects that interact

Loosely couples designs allow us to build a flexible OO system that can handle change because they minimize the interdependency between objects.

When to Use?

When you need many other objects to receive the update when another object changes

Pros ( 👍 ) & Cons ( 👎 )

👍 Loose coupling - Subject ( Publisher ) doesn't need to know about the Observer ( Subscriber ).

👍 You can establish relations between objects at runtime.

👍 Changes to either the subject or an observer will not affect the other.

👎 Subject ( Publisher ) may send the updates that don't matter to the observer ( Subscriber ).

Code

With Java's built-in support all you have to extend observable and tell it when to notify the observers. The API does the rest for you. Check it out java.util.Observer, java.util.Observable but this is deprecated from java 9. The event model supported by Observer and Observable is quite limited, the order of notifications delivered by Observable is unspecified, and state changes are not in one-for-one correspondence with notifications. For a richer event model, consider using the java.beans package. For reliable and ordered messaging among threads, consider using one of the concurrent data structures in the java.util.concurrent package.

Reference

Last updated