Callbacks
There is more than one way for one object to ask another for data.
Here we compare the situation to a detective asking questions about
a murder. When he arrives on the scene, he asks the witness if he/she
can recall anything about the murder and gets an immediate answer.
See, the method: doYouKnowAnythingAboutTheMurder()
But witnesses don't always think of everything right on the spot, so
a detective will likely give them a business card with a phone number
on it so that the witness can "call back" the detective and provide
additional information. There is no predicting when, if ever, or how
many times the witness might think of additional clues. The callback
object (the business card) provides a mechanism.
This situation is not unlike the way the graphics system processes
mouse clicks. In this case, the graphics system is the witness (i.e.
it sees the events happening). You are like the detective, and you
provide a MouseAdapter as a callback object to process the mouse
clicks.
BusinessCard.java |
1 | interface BusinessCard { |
2 | public void phoneTip(String iThoughtOfSomething); |
3 | } |
$ javac BusinessCard.java
|
Witness.java |
1 | public class Witness { |
2 | BusinessCard bc; |
3 | public String doYouKnowAnythingAboutTheMurder() { |
4 | return "I saw his wife threatening to kill him."; |
5 | } |
6 | public void callMeIfYouThinkOfAnythingAboutTheMurder(BusinessCard bc) { |
7 | this.bc = bc; |
8 | } |
9 | public void thinkOfSomething() { |
10 | bc.phoneTip("I saw his wife drop "+ |
11 | "a knife into the garbage "+ |
12 | "behind the house"); |
13 | } |
14 | } |
$ javac Witness.java
|
Detective.java |
1 | public class Detective { |
2 | String[] notes = new String[10]; |
3 | int nextNote = 0; |
4 | void addNote(String note) { |
5 | notes[nextNote++] = note; |
6 | } |
7 | |
8 | BusinessCard card = new BusinessCard() { |
9 | @Override |
10 | public void phoneTip(String tip) { |
11 | addNote(tip); |
12 | } |
13 | }; |
14 | |
15 | public static void main(String[] args) { |
16 | Detective d = new Detective(); |
17 | |
18 | Witness witness = new Witness(); |
19 | |
20 | // Meet and interrogate the witness. |
21 | d.addNote(witness.doYouKnowAnythingAboutTheMurder()); |
22 | |
23 | // Give the witness your card.. |
24 | witness.callMeIfYouThinkOfAnythingAboutTheMurder(d.card); |
25 | |
26 | // A few days later... |
27 | witness.thinkOfSomething(); |
28 | |
29 | for(int i=0;i<d.nextNote;i++) |
30 | System.out.println(d.notes[i]); |
31 | } |
32 | } |
$ javac Detective.java
| $ java Detective
I saw his wife threatening to kill him.
I saw his wife drop a knife into the garbage behind the house
|
|