An interviewer asked me:
What isandObserver
and when should we use them?Observable
Observer
Observable
1)is a class andObservable
is an interface.Observer
2)class maintain a list of Observers.Observable
3) When an Observable object is updated, it invokes themethod of each of its Observers to notify that, it is changed.update()
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);
}
}
Observer
Observable
setChanged()
notifyObservers(message)
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.