Observer design pattern in java

As the name suggests it is used for observing some objects.Observer watch for any change in state or property of subject.Suppose you are interested in particular object and want to get notified when its state changes then you observe that object and when any state or property change happens to that object,it get notified to you.

As described by GoF:
“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically”.

You can think of observer design pattern in two ways

  • Subject-Observer relationship:Object which is being observed is refereed as Subject and classes which observe subject are called Observer
  • Publisher-Subscriber relationship:A publisher is one who publish data and notifies it to the list of subscribers who have subscribed for the same to that publisher. A simple example is Newspaper. Whenever a new edition is published by the publisher,it will be circulated among subscribers whom have subscribed to publisher.

The observers will not monitor every time whether there is any change in state of subject or not, since they will be notified for every state change of subject, until they stop observing subject. So it follows hollywood principle-“Don’t call us,we will call you”.

Some real life examples:

You might have surfed “ megastore”.So when you search for any product and it is unavailable then there is option called “Notify me when product is available”.If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail “Product is available now you can buy it”.In this case,Product is subject and You are an observer.
Lets say,your permanent address is changed then you need to notify passport authority and pan card authority.So here passport authority and pan card authority are observers and You are a subject.

On facebook also,If you subscribe someone then whenever new updates happen then you will be notified.

When to use it:

  • When one object changes its state,then all other dependents object must automatically change their state to maintain consistency
  • When subject doesn’t know about number of observers it has.
  • When an object should be able to notify other objects without knowing who objects are.

 UML diagram for observer design pattern:



  • Knows its observers
  • Has any number of observer
  • Provides an interface to attach and detaching observer object at run time


  • Provides an update interface to receive signal from subject


  • Stores state of interest to ConcreteObserver objects.
  • Send notification to it’s observer


  • Maintains reference to a ConcreteSubject object
  • Maintains observer state consistent with subjects.
  • Implements update operation

Java in-built API for observer pattern:

The java API provides one class and one inteface for implementing observer pattern.
1. java.util.Observable-class
2. java.util.Observer-interface


For being observed,class must extend this class. The subclass becomes observable and override methods of  java.util.Observable and other objects can “observe” changes in state of this object.
addObserver(Observer o) :add Observer to the list of observers for this subject.
deleteObserver(Observer o) :delete Observers from the list of observers .
notifyObservers() : notify all the observers if object has changed.
hasChanged() :return true if object has changed.
setChanged() :This method marks object has changed
clearChanged() :this method will indicate that subject has no changes or all the observers has been notified.


The class that performs the “observing” must implement the java.util.Observer interface. There is a single method:
public void update(Observable obj, Object arg) :This method is called whenever the observed object is changed. An application calls an Observable object’s notifyObservers method for notifying to all the observers of change.


You might have surfed “ megastore”.So when you search for any product and it is unavailable then there is option called “Notify me when product is available”.If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail “Product is available now you can buy it”.

Java code:

Below interface is our subject interface.It consists of method for adding or removing observers and also in condition of state change,notify all observer.

Below class is our ConcreteSubject class.It implements subject interface thus provide implementation of all above three methods.

 Below interface is our observer interface.It consists of single method called “update”

Below class is our ConcreteObserver class.It implements observer interface and provide implementation for update and other ConcreteObserver specific methods.

Run it:

Now in above program,when availability of samsung mobile changes,it get notified subscribers who has subscribed for it.

Using java inbuilt APIs:

Run it:

Some important points about observer pattern:

  • Loose coupling between Subject and Observer:Only thing subject know about its observers is that observer implements Observer interface.You can register or delete any observer without affecting subject.
  • Support for broadcast communication:Notification about subject state change does not need to specify its receiver.This notification is broadcasted to all interested object that subscribed to it.
  • The one of the problem with this pattern is that debugging become very hard,if you have large number of subscribers because flow of control is implicit between subject and observers.
  • Spurious updates:If criteria for state change is not well defined then sometimes it lead to spurious updates.

Source code:

Was this post helpful?

Related Posts

  • 25 April

    Strategy design pattern in java

    Table of ContentsStrategy design pattern exampleStrategy pattern example In this post, we will see about Strategy design pattern in java. Strategy design pattern allows us to change algorithm implementation at runtime.Strategy design pattern provides multiple algorithms and client can choose algorithm based on their needs with the help of composition. Strategy design pattern example Let’s […]

  • 24 April

    Singleton design pattern in java

    Table of ContentsSingleton classEager initializationLazy initializationThread safe SingletonDouble check lockingBill Pugh Singleton ImplementationCreate singleton using EnumTesting singleton with ReflectionTesting singleton with SerializationTesting singleton with Cloning. In this post, we will see about Singleton design pattern in java. Singleton design pattern is one of the simplest design pattern but singleton property can be broken using multithreading, […]

  • 14 July

    How to use connection pool using service locator design Pattern in java

    In this post, you will learn about the Connection Pool. This post is intended by java application development experts for entire development community to let people learn and acknowledge about Connection Pool and how to use its object using Service Locator design pattern. Introduction Connection pool is a mechanism which applicable for all technologies in […]

  • 01 March

    Template method design pattern in java

    Table of ContentsExample:Used in java API:Source code: CodeProjectTemplate method pattern is a behavioral design pattern which provide base method for algorithm,called template method which defers some of its steps to subclasses So algorithm structure is same but some of its steps can be redefined by subclasses according to context. Template means Preset format like HTML […]

  • 29 September

    Builder design pattern in java

    Table of ContentsGeneric UML diagram for builder design pattern:Elements:When to use it:WorkFlow:Example: Builder design pattern allows to create complex object step by step and also enforces a process to create an object as a finished product.Construction of object should be such that same construction process can create different representations.Director controls the construction of object and […]

  • 28 September

    Proxy design pattern in java

    Table of ContentsWhen to use it:UML diagram for proxy design pattern:Elements:WorkFlow:Example:Source code: CodeProjectProxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object’s code. As described by GoF: “Provide a […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.