Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 4 of 5
// In file eventgui/ex1/AnsweringMachine.java
public class AnsweringMachine
implements TelephoneListener {
public void telephoneRang(TelephoneEvent e) {
System.out.println("AM hears the phone ringing.");
}
public void telephoneAnswered(TelephoneEvent e) {
System.out.println("AM sees that the phone was answered.");
}
}
// In file eventgui/ex1/Person.java
public class Person {
public void listenToPhone(Telephone t) {
t.addTelephoneListener(
new TelephoneAdapter() {
public void telephoneRang(TelephoneEvent e) {
System.out.println("I'll get it!");
}
}
);
}
}
Note that AnsweringMachine implements the TelephoneListener interface directly. By contrast, the Person object instantiates an anonymous inner class that subclasses the TelephoneAdapter class. This anonymous inner class overrides the only method of interest to the Person object: telephoneRang().
The last class we need to define is an example application that will exercise all these classes and interfaces:
// In file eventgui/ex1/Example1.java
public class Example1 {
public static void main(String[] args) {
Telephone ph = new Telephone();
Person bob = new Person();
AnsweringMachine am = new AnsweringMachine();
ph.addTelephoneListener(am);
bob.listenToPhone(ph);
ph.ringPhone();
ph.answerPhone();
}
}
When executed, the Example1 application prints out:
The answering machine hears the phone ringing. I'll get it! The answering machine sees that the phone was answered.
Implementation guidelines
With the guidelines I list in this section, I am trying to define a default way to implement this idiom. I say default because,
unless you have a specific reason to take a different implementation approach, you should automatically use the approach recommended
in these guidelines. My theory is that if you adhere closely to the default implementation approach, it will be easier for
your fellow programmers to recognize the idiom in your work. More importantly, I feel that such idiom recognition will make
it easier for your fellow programmers to understand, use, and change your code.
On the other hand, you should feel free to depart from the default approach to implementing the idiom when you feel it makes sense. In fact, I myself describe two potential "variants" to the default approach in the next section.
Now, on to the guidelines:
fire method should go through the list of listeners and invoke the appropriate handler method upon one listener after the other.Variants
The following are variants to the default approach to implementing idioms: