Professional Documents
Culture Documents
While we believe that this content benefits our community, we have not yet thoroughly reviewed
it. If you have any suggestions for improvements, please let us know by clicking the “report an
issue“ button at the bottom of the tutorial.
Observer Pattern is one of the behavioral design pattern. Observer design pattern is useful
when you are interested in the state of an object and want to get notified whenever there is
any change. In observer pattern, the object that watch on the state of another object are
called Observer and the object that is being watched is called Subject.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Observer Design Pattern
For our observer pattern java program example, we would implement a simple topic and
observers can register to this topic. Whenever any new message will be posted to the topic,
all the registers observers will be notified and they can consume the message. Based on the
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
requirements of Subject, here is the base Subject interface that defines the contract
methods to be implemented by any concrete subject.
package com.journaldev.design.observer;
Next we will create contract for Observer, there will be a method to attach the Subject to the
observer and another method to be used by Subject to notify of any change.
package com.journaldev.design.observer;
Now our contract is ready, let’s proceed with the concrete implementation of our topic.
package com.journaldev.design.observer;
import java.util.ArrayList;
import java.util.List;
public MyTopic(){
hi b A Li ()
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
this.observers=new ArrayList<>();
}
@Override
public void register(Observer obj) {
if(obj == null) throw new NullPointerException("Null Observer");
synchronized (MUTEX) {
if(!observers.contains(obj)) observers.add(obj);
}
}
@Override
public void unregister(Observer obj) {
synchronized (MUTEX) {
observers.remove(obj);
}
}
@Override
public void notifyObservers() {
List<Observer> observersLocal = null;
//synchronization is used to make sure any observer registered aft
synchronized (MUTEX) {
if (!changed)
return;
observersLocal = new ArrayList<>(this.observers);
this.changed=false;
}
for (Observer obj : observersLocal) {
obj.update();
}
@Override
public Object getUpdate(Observer obj) {
return this.message;
}
The method implementation to register and unregister an observer is very simple, the extra
method is postMessage() that will be used by client application to post String message to
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
the topic. Notice the boolean variable to keep track of the change in the state of topic and
used in notifying observers. This variable is required so that if there is no update and
somebody calls notifyObservers() method, it doesn’t send false notifications to the
observers. Also notice the use of synchronization in notifyObservers() method to make sure
the notification is sent only to the observers registered before the message is published to
the topic. Here is the implementation of Observers that will watch over the subject.
package com.journaldev.design.observer;
@Override
public void setSubject(Subject sub) {
this.topic=sub;
}
Notice the implementation of update() method where it’s calling Subject getUpdate() method
to get the message to consume. We could have avoided this call by passing message as
argument to update() method. Here is a simple test program to consume our topic
implementation.
package com.journaldev.design.observer;
//create observers
Observer obj1 = new MyTopicSubscriber("Obj1");
Ob bj2 M T i S b ib ("Obj2")
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Observer obj2 = new MyTopicSubscriber("Obj2");
Observer obj3 = new MyTopicSubscriber("Obj3");
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Observer design pattern is also called as publish-subscribe pattern. Some of it’s
implementations are;
java.util.EventListener in Swing
javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
That’s all for Observer design pattern in java, I hope you liked it. Share your love with
comments and by sharing it with others.
If you’ve enjoyed this tutorial and our broader community, consider checking out our
DigitalOcean products which can also help you achieve your development goals.
Learn more here
Join our DigitalOcean community of over a million developers for free! Get help and
share knowledge in our Questions & Answers section, find tutorials and tools that will
help you grow as a developer and scale your project or business, and subscribe to
topics of interest.
Sign up now
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
About the authors
Pankaj Author
Developer and author at DigitalOcean.
Ask a question
Search for more help
Comments
JournalDev
August 3, 2021
Very nice article, ofcourse all design pattern articles. One small correction, after
notifyObservers();, you should nullify this.message, so that getUpdate should be
returned null.
Rajes Badam
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
JournalDev
January 18, 2021
Please provide simple example to return the observed data to different web client
Gomathi
JournalDev
June 25, 2020
Hi Pankaj Sir, nice explanation, but one thing that is bothering me is why did the client
is calling the update() method? it is infact the Observable that should be triggering
that method call.
- rajsekhar
JournalDev
June 15, 2020
Observer Pattern is not Pub-Sub Pattern. Pub-Sub pattern involves message broker or
event bus or topic between publisher and subscribers. Please update
Sid
JournalDev
November 26, 2019
Its a nice explanation.Just got below concern what is the purpose of getUpdate
method of observer interface having observer as argument is not clear to me. We are
not using that inside method, i think getUpdate() is also fine Could you please suggest!
Satyabrata Mohanty
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
JournalDev
October 6, 2019
thanks for this.very well explained
Jay
JournalDev
July 14, 2019
Thank you a lot
- omid
JournalDev
August 14, 2018
What is MUTEX object used for
Kunal Dada
Show replies
JournalDev
March 9, 2018
You said that “Subject also contain a method to notify all the observers of any change
and either it can send the update while notifying the observer or it can provide another
method to get the update.” How do we decide which implementation to use ? I am
guessing that if some of the observers only care that update has happened, but don’t
care what was the update, then just update() is useful. If some are interested in what
was updated, then update(Object updateInfo) makes sense. Also, why are we passing
observer inside getUpdate(Observer obj) ? Maybe observable can use that to track
which all observers got the message ?
John
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
JournalDev
March 9, 2018
It would be helpful to put a comment for why public void unregister(Observer obj) has
a synchronized block, It is because you cannot add elements to arraylist and also
remove elements from it at the same time. It will give a
java.util.ConcurrentModificationException.
John
Show replies
This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International
License.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com