Observer Pattern

The Observer pattern is a software design pattern in which an object (subject / Observable), maintains a list of Observers, and notifies them automatically of any state changes [wiki]. The Observer pattern falls under behavioral pattern category.

When it is used

Observer Pattern (alias as Alias: Subject Observer, Publish Subscribe, Callback) is used when there is a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. The change of a state in one object must be reflected in another object without keeping the objects tight coupled. It is easy to support new observers with minimal code changes.

Here is one scenario: a configuration file (server_setting.xml) is monitored by an Observable object. When the configuration file is modified by someone, the Observable will detect the file modification, and notify multiple Observers about the file change. Once the Observers receive the notification, one observer will reload the file without restarting the application (/server), another observer may send alert message to the system administrator about the change.

Observer Pattern is part of other important patterns (e.g. Model View Controller), and also the basis for publish-subscribe messaging architectures.

Implementation

See the diagram.
Observer Pattern

The participants in the diagram are:

  • Observer – interface defining the operations to be executed after receiving notification
  • ObserverA – Observer implementation
  • ObserverB – Observer implementation
  • Observable (Subject) – interface defining the operations for registering and unregistering observers
  • ObservableA – Observable implementation. It maintains the state of the object, and notifies the attached Observers once the state changes.

By the way, Java SDK provides Observable API. We will implement our own interface to help understand the Observer pattern.

Code Examples

Client class:

logging:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

One thought on “Observer Pattern

  1. Pingback: Software Design Patterns

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">