Observer Pattern in Java with example.

Let us answer some of the questions related to Observer Pattern in this post that is asked in the core java interview.
What is Observer pattern?
When and why to use this pattern?
How to implement Observer Pattern in java?Now consider the following situation and issues.

     1. When many objects depend on other object, the state change of the other object needs to be updated  to all dependent objects to maintain consistency between these objects.
     2.  At the same time , we need to achieve the above updation by making these objects loosely coupled (de-coupled) which reduces dependency and allows to reuse these objects independently .
     One of the easiest way to notify / update the state change to the dependent objects is to call them directly as given below. But direct calling between objects increases dependency between their objects which can not be reused independently. See the below code , a bad design
class NoticeBoard {
   private String notice;
   private ArrayList<Employee> subscribers = new ArrayList<Employee>();

   public void subscribe(Employee observer) {

   public void updateNoticeBoard( String notice ) {
        this.notice = notice;
           for (Employee s : subscribers) {
/* public void updateNoticeBoard1( String notice ) {
this.notice = notice;
Employee emp1 = new Employee( );
Employee emp2 = new Employee( );
}  */

class Employee {
      public void update( String arg) {
             System.out.println( "Notice Board Updated: " + arg );

      In the above code, NoticeBoard and Employee are dependent. When there is a update in the NoticeBoard, it is updated to all employees who have registered. Employee object is created within updateNoticeBoard or updateNoticeBoard1 method and update method of employee object is called. This direct calling between objects increases dependency. For example, when you change the name of the class Employee, you have to change in all the places where employee object is created in NoticeBoard class.

So the generic solution for the above situations to maintain consistency between related objects and to decrease the dependency between objects, would be the Observer Pattern which is a nice pattern.

Observer Pattern is a commonly used pattern in core java .

Observer pattern involves a subject that has multiple views (observers). Each view object needs to be updated whenever the subject changes or  In other words we can also say that the object containing the data (subject ) is separate from the objects that displays the data (observers ), and these display objects observe changes on that data. These behavior can be seen in some of the real life applications.


1. Google Alerts : New user can subscribe for an update on a particular subject in the web , google notifies all subscribers when there is a update on the subject in the web . Existing subscriber can unsubscribe if they don’t wan’t updates.
2. Some application showing TextView and Scroll View of any counter or any other numeric result. Both TextView and Scroll View are observers that observe the data change to update text and graphical view.

3. In excel, average() and sum() function can be dependent on the same data object and therefore the change in the data should be notified to these functions to display the correct result. Both can be reused independantly.


This pattern is also called Dependents, Publish-Subscribe, Model-View. Observer Pattern is used with MVC architecture where subject Model plays the role of Subject and the View represents the Observer. MVC pattern helps separation of business data (the model) and the presentation logic (the view). When the model changes, the system must notify the view about the model’s state

Now let us see How to implement Observer Pattern in Java ?
The Observer pattern can be implemented by the built-in Java Observer Pattern using java.util.Observable and java.util.Observer. You can also implement by your own code.
The java.util package provides a built-in implementation of the Observer pattern using the Observable class and Observer interface

interface Observer : (View in the model-view architecture)
An interface which is implemented as observer objects . In other words we can say, an observer is any object that implements interface Observer . This interface contains only one method update which is called by the Observable to update the state change of the Subject (Observable object) to observer objects.

Syntax : void update(Observable o, Object arg);

java.util.Observable : (data in the model-view architecture)

This class represents a Subject which is an observable object. The object needs to have observed has to extend the class Observable . An observable object can have more than one observers. All the list of observers registered / subscribed with Observable object are notified when there is a state change in the Subject.

Some of the methods of Observable Class :
addObserver() : Adds an observer object to the set of observers , where all observer objects in the Set are unique.

clearChanged() : Indicates that the subject has no changes, or that it has already notified all changes to all observers

countObservers() : Returns the number of observers added in the Observable object.

deleteObserver() / deleteObservers() : Removes an observer / all observers from the set of observers

hasChanged() : Returns true if the subject object has any change to be updated to observers.

notifyObservers() : Checks for the change in the Subject (state change in the Observable object), if there is any change ,it is notified to all of its observers then call the clearChanged method to indicate the subject has no changes.

setChanged() : Marks this Observable object as having been changedFirst let us see the code example of Observer Pattern using ready made implementation of Java.

Example 1:
Consider the Notice Board of an organization. NoticeBoard object represents the Subject. Employee can subscribe for the notice board updation. Whenever the notice board is updated, all the employees who have subscribed are notified the change.

Two main classes are created. NoticeBoard class which extends Observable. Employee class which implements observer. Both are related objects and having less dependency . Both objects can be reused independently. NoticeBoard knows about the list of subscribers only and does know about the actual implementation

import java.util.Observable;
import java.util.Observer;
class NoticeBoard extends Observable {
    private String notice;
    public String getNotice( ) {
        return notice;
    public void updateNoticeBoard( String notice ) {
      this.notice = notice;
      setChanged( );
      notifyObservers( notice );

class Employee implements Observer {
      public void update(Observable o, Object arg) {
      System.out.println( "Notice Board Updated: " + arg );

public class ObserverPatternTest3
   public static void main( String [] args ) {
          NoticeBoard noticeBoard = new NoticeBoard( );
          Employee emp1 = new Employee( );
          Employee emp2 = new Employee( );
          Employee emp3 = new Employee( );
          noticeBoard.addObserver( emp1 );
          noticeBoard.addObserver( emp2 );
          noticeBoard.addObserver( emp3 );
          noticeBoard.updateNoticeBoard("Farewell party for Mr. ABC on 30th April 2012 in the Canteen. All of you are requested to attend the Party");


Example 2:

              Now let us write code for own implementation of Observer Pattern. For example, Gold / Silver prices are updated on daily basis. People will buy gold / silver when the price is low. People will sell the gold / silver when the price is high. So they need price updation when there is a change in price . For that , they have to subscribe to PriceUpdate (an object being observed). 

import java.util.ArrayList;

interface Observer{
       public void update(String item, float price);

interface Observable{
       public void subscribe(Observer observer);
       public void unSubscribe(Observer observer);
       public void notifyObservers();

class PriceUpdate implements Observable {
       private ArrayList&lt;Observer&gt; observers = new ArrayList&lt;Observer&gt;();
       private String item;
       private float price;

       public PriceUpdate(String item, float price) {
              this.item = item;
              this.price = price;

       public float getPrice() {
              return price;

       public void setPrice(float price) {
              this.price = price;

       public String getItem() {
              return this.item;

       public void subscribe(Observer observer) {
        if (observer == null)
            throw new NullPointerException();
        if (!observers.contains(observer))   

       public void unSubscribe(Observer observer) {
            System.out.println("One Person Unsubscribed ");

       public void notifyObservers() {
              for (Observer s : observers) {
                     s.update(this.item, this.price);

class Subscriber  implements Observer {
           String subscriberName;
           public Subscriber(String name) {this.subscriberName=name;   } 
           public void update(String item, float price) {
              System.out.println("Hello Mr. " + this.subscriberName + "!  Price Updation : " + item+" price today is  " + price);

public class ObserverPatternTest2 {

       public static void main(String args[]) {
             Subscriber subGold1  = new Subscriber("Kumar");
             Subscriber subGold2  = new Subscriber("Kannan");
             Subscriber subGold4  = new Subscriber("Kannan");
            PriceUpdate  priceUpdateGold = new PriceUpdate("Gold", 21000f);  //Seperate subject


              Subscriber subSilver1  = new Subscriber("ABC");
              Subscriber subSilver2  = new Subscriber("XYZ");
              Subscriber subSilver3 = new Subscriber("Akash");

            PriceUpdate  priceUpdateSilver= new PriceUpdate("Silver", 21.50f);  //Seperate subject


             Subscriber subGold3  = new Subscriber("VKJ");

              priceUpdateGold.unSubscribe(subGold2);  // unsubscribe 



Note : 1. Java interface plays a major role in implementation of Observer Pattern.
2. In the above code , Duplicate objects are not accepted . Two different objects with same name will be accepted. Methods like subscribe, unSubscribe and notifyObservers of PriceUpdate class can be synchronized for thread-safe.


Leave a Reply