Home  >  Design Pattern

Example of Observer Design Pattern in java

By Arvind Rai, December 03, 2013
To understand Observer Design Pattern, we will take one real time example. We read newspaper. We get the daily news by news paper. Here we are the observer and the news paper is observable. Observer Design Pattern keeps the data of its entire listener and whenever there is any change it notifies to its listener. Speaking clock is another example of Observer Design Pattern. Speaking clock notifies when it finishes one hour. So there are many real life example in which one is observable and other is observer. Get more by the below figure.
Example of Observer Design Pattern in java
In our example we will show observer design pattern by news reader as observer and news as observable.

How Observer Design Pattern Works in Java

In java to implement Observer Design Pattern, we need to understand two API java.util.Observable class and java.util.Observer interface. Observable works on model view paradigm. We can subclass it to make any class Observable. Now the instance of Observable can be observed by more than one observer. Any class implementing Observer interface can be an observer. Observer has method to get update and that method is called by observable. Every observer needs to register to observable object so that Observable object has the information whom to notify.
java.util.Observe
update(Observable o, Object arg): This method is called whenever the observable object has any change.
java.util.Observable
Some method of Observable which plays the important role for Observer Design Pattern.
addObserver(Observer o) : All observers are added to the list of observable object.
notifyObservers() : Observable object notifies the observer by this method.

Create Observer in Java

In our example two NewsReader are observers. To implement observer, NewsReader class will implement Observer and update method has been defined.
FirstNewsReader.java
package com.concretepage;
import java.util.Observable;
import java.util.Observer;
public class FirstNewsReader implements Observer {
    public void update(Observable obj, Object arg) {
        System.out.println("FirstNewsReader got The news:"+(String)arg);
    }
}
 
SecondNewsReader.java
package com.concretepage;
import java.util.Observable;
import java.util.Observer;
public class SecondNewsReader implements Observer {
    public void update(Observable obj, Object arg) {
        System.out.println("SecondNewsReader got The news:"+(String)arg);
    }
}
 

Create Observable in java

In our example News is observable. News class extends Observable. There is some list of news which needs to be notified to observer. To notify observer notifyObservers() method has been called.
News.java
package com.concretepage;
import java.util.Observable;
public class News extends Observable {
    void broadcast() {
        String[] news = {"News 1", "News 2", "News 3"};
        for(String s: news){
            //set change
            setChanged();
            //notify observers for change
            notifyObservers(s);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Error Occurred.");
            }
        }
    }
}

Run Observer and Observable

Two run the above example we need another class. In this class we have instantiated the news readers as observer. And also create the instance of Observable. Two observers have been added to observable object. Then observable object is broadcasting the news to all its observers.
ObserverExample.java
package com.concretepage;
public class ObserverExample {
    public static void main(String args[]) {
        News observedNews = new News();
        FirstNewsReader reader1 = new FirstNewsReader();
        SecondNewsReader reader2 = new SecondNewsReader();
        observedNews.addObserver(reader1);
        observedNews.addObserver(reader2);
        observedNews.broadcast();
    }
}
 


Output
SecondNewsReader got The news:News 1
FirstNewsReader got The news:News 1
SecondNewsReader got The news:News 2
FirstNewsReader got The news:News 2
SecondNewsReader got The news:News 3
FirstNewsReader got The news:News 3
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us