Ravi Ravi - 1 month ago 14
Java Question

When should we use Observer and Observable

An interviewer asked me:


What is
Observer
and
Observable
and when should we use them?


I wasn't aware of these terms, so when I came back to home and I started Googling about
Observer
and
Observable
and found some points from different resources:


1)
Observable
is a class and
Observer
is an interface.

2)
Observable
class maintain a list of Observers.

3) When an Observable object is updated, it invokes the
update()
method of each of its Observers to notify that, it is changed.


I found this example:

import java.util.Observable;
import java.util.Observer;

class MessageBoard extends Observable {
private String message;

public String getMessage() {
return message;
}

public void changeMessage(String message) {
this.message = message;
setChanged();
notifyObservers(message);
}

public static void main(String[] args) {
MessageBoard board = new MessageBoard();
Student bob = new Student();
Student joe = new Student();
board.addObserver(bob);
board.addObserver(joe);
board.changeMessage("More Homework!");
}
}

class Student implements Observer {
public void update(Observable o, Object arg) {
System.out.println("Message board changed: " + arg);
}
}


But I don't understand why we need
Observer
and
Observable
? What are the
setChanged()
and
notifyObservers(message)
methods for?

Answer

You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.

Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. Same idea. In that case, you Twitter account is the Observer and the person you're following is the Observable.

The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.