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 got back home and started Googling about Observer and Observable, I found some points from different resources:
1)
Observableis a class andObserveris an interface.2) The
Observableclass maintains a list ofObservers.3) When an
Observableobject is updated, it invokes theupdate()method of each of itsObservers to notify that, it is changed.
I found this example:
import java.util.Observable;
import java.util.Observer;
class MessageBoard extends Observable
{
public void changeMessage(String message)
{
setChanged();
notifyObservers(message);
}
}
class Student implements Observer
{
@Override
public void update(Observable o, Object arg)
{
System.out.println("Message board changed: " + arg);
}
}
public class MessageBoardTest
{
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!");
}
}
But I don’t understand why we need Observer and Observable? What are the setChanged() and notifyObservers(message) methods for?
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. In that case, your 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.