Pages

Observer design patternin Java is a fundamental core Java pattern where Observe watch for any change in state or property of Subject. For Example Company updates all its shareholders for any decision they make here Company is Subject and Shareholders are Observers, any change in policy of company and Company notifies all its Shareholders or Observer. This was simple real world explanation of Observer pattern. In this article we will in detail what is Observer Design pattern, what is benefit of Observer design Pattern, Example or Observer pattern in Java and few other points. Just like Decorator design Pattern and Factory Pattern in Java, Observer pattern is also used in JDK.

Observer design Pattern Java Code Example

What is Observer design Pattern?

Observer design pattern in Java is very important pattern and as name suggest it’s used to observe things. Suppose you want to notify for change in a particular object than you observer that object and changes are notified to you. Object which is being observed is refereed as Subject and classes which observe subject are called Observer. This is beautiful pattern and used heavily along with Model View Controller Design pattern where change in model is propagated to view so that it can render it with modified information. Observer pattern is also a very popular Java interview questions and mostly asked on Senior or mid senior level.

Problem which is solved by Observer Pattern:

If we have requirement that if particular object change its state and on depending upon

This changes some or group of objects automatically change their state we need to implement observer pattern it will reduce coupling between objects.

In real world if try to find example see when we subscribe for New Phone connection whenever customer is registered with that company all other departments are notified accordingly and then depending upon the state the do their jobs like do the verification of their address then if customer state is verified then dispatch the welcome kit etc.

How Observer Design Pattern is implemented in Java;

For implementation of this pattern java makes our task very easy, developer need not to do so much for implementing this pattern .In java.util package we can find interfaces ,classes and methods for implementing this pattern.

Public Interface Observer:

Any class who implements this interface must be notified when subject or observable object change its status.

Update (Observable Ob, Object arg): This method is called when subject is changed.

Class Observable:

It’s a subject to whom observer wants to observe.

Some Important Method:

addObserver(Observer o):add Observers in the set of observers for this subject or observalbel object.

deleteObserver(Observer o): delete Observers in the set of observers .

hasChanged():check if object has changed.

clearChanged():this method will indicate that subject has no changes or all the observers has been notified when changes is made.

notifyObservers(): notify all the observers if object has changed .

Code Example of Observer design pattern in Java:

Observer Design pattern is generic than how it is implemented in Java. You are free to choose java.util.Observable or java.util.Observer or writing your own Subject and Observer interface. I prefer having my own Subject and Observer interface and this is how I am going to write my Code Example of Observer design Pattern in java. Mine Example is very Simple you have a Loan on which interest rate is subject to change and when it changes, Loan notifies to Newspaper or Internet media to display new loan interest rate. To implement this we have a Subject interface which contains methods for adding, removing and notifying Observers and an Observer interface which contains update(int interest) method which will be called by Subject implementation when interest rate changes.

import java.util.ArrayList;

interface Observer {

publicvoid update(float interest);

}

interface Subject {

publicvoid registerObserver(Observer observer);

publicvoid removeObserver(Observer observer);

publicvoid notifyObservers();

}

class Loan implements Subject {

private ArrayList<Observer> observers = new ArrayList<Observer>();

private String type;

privatefloatinterest;

private String bank;

public Loan(String type, float interest, String bank) {

this.type = type;

this.interest = interest;

this.bank = bank;

}

publicfloat getInterest() {

returninterest;

}

publicvoid setInterest(float interest) {

this.interest = interest;

notifyObservers();

}

public String getBank() {

returnthis.bank;

}

public String getType() {

returnthis.type;

}

@Override

publicvoid registerObserver(Observer observer) {

observers.add(observer);

}

@Override

publicvoid removeObserver(Observer observer) {

observers.remove(observer);

}

@Override

publicvoid notifyObservers() {

for (Observer ob : observers) {

System.out

.println("Notifying Observers on change in Loan interest rate");

ob.update(this.interest);

}

}

}

class Newspaper implements Observer {

@Override

publicvoid update(float interest) {

System.out.println("Newspaper: Interest Rate updated, new Rate is: "

+ interest);

}

}

class Internet implements Observer {

@Override

publicvoid update(float interest) {

System.out.println("Internet: Interest Rate updated, new Rate is: "

+ interest);

}

}

publicclass ObserverTest {

publicstaticvoid main(String args[]) {

// this will maintain all loans information

Newspaper printMedia = new Newspaper();

Internet onlineMedia = new Internet();

Loan personalLoan = new Loan("Personal Loan", 12.5f,

"Standard Charterd");

personalLoan.registerObserver(printMedia);

personalLoan.registerObserver(onlineMedia);

personalLoan.setInterest(3.5f);

}

}

Advantage of Observer Design Pattern in Java:

Main advantage is loose coupling between objects called observer and observable. The subject only know the list of observers it don’t care about how they have their implementation.All the observers are notified by subject in a single event call as Broadcast communication

Disadvantage of Observer Design Pattern in Java:

·The disadvantage is that the sometime if any problem comes, debugging becomes very difficult because flow of control is implicitly between observers and observable we can predict that now observer is going to fire and if there is chain between observers then debugging become more complex.

·Another issue is Memory management because subject will hold all the reference of all the observers if we not unregister the object it can create the memory issue.

That’s all on Observer Pattern in Java. Share your thought how and when you have used Observer Pattern in your Project and any issue you have faced?

Hi Anonymous, It should not give any compilation error as Internet and NewsPaper both implements observer. I think you might have imported java.util. Observer instead of my custom interface Observer and that causing error. let me know if that's not the case. if you post error , we can take a look.

A good post on observers! But still most developers unaware its very very simple to use observer pattern in JavaEE without implementing those. Of course the app should already be running on a JavaEE server bu that is also easy with the new TomEE and glassfish...There is a good tutorial on JavaEE implementation of Observers here:http://blogs.eteration.com/blog/?p=1299 and here: http://blogs.eteration.com/blog/?p=1305

Thanks for your comment morphy, you got it right, setChanged() has its place otherwise it would result it would lead to unnecessary updates to Observable and I also agree that using JDK's Observable/Observer API is good idea, but as learning point of view I see if you understand the pattern by your own example and than compare to what API provides to you.

Hi nice article , is it the same thing for example when i post any my status it broadcasted to all people depending on privacy ? can you give any practical example or where we should use it or it is being used ?

Interesting article, but I wanted to query the use of ArrayList for storing observers. This means an observer can be stored more than once. Remove will only remove the first instance of the same observer, in this case. Perhaps using a Set is better?

Hi, good article Javin, this article is to tell us what is the actually structure,flow and glow of "Observer pattern" that's it. How robust one gone going to implement it is there knowledge base. Like one said use Set instead of ArrayList, and change the code of setIntereset() function for efficiency there could be many much more like thread safety, concurrency and all. But that all now up to programmer. Once again thanks @Javin for sharing conceptual knowledge.

very good explanation , but there seems to be an error related to Generics child observers can't be added to List , this is against generics because in generics List is not a superset of List , please correct me if i am wrong