|
|
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 4
Using the CoR pattern for event handling was doomed to failure because event handling requires subclassing components. Because an average graphical user interface (GUI) uses many components, and most components are interested in at least one event (and some are interested in many events), AWT developers had to implement numerous component subclasses. Generally, requiring inheritance to implement a heavily used feature is poor design, because it results in an explosion of subclasses.
The original AWT event model was eventually replaced with the Observer pattern, known as the delegation model, which eliminated the CoR pattern. Here's how it works:
import java.awt.*;
import java.awt.event.*;
public class MouseSensor extends Frame {
public static void main(String[] args) {
MouseSensor ms = new MouseSensor();
ms.setBounds(10,10,200,200);
ms.show();
}
public MouseSensor() {
Canvas canvas = new Canvas();
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("mouse down");
}
public void mouseReleased(MouseEvent e) {
System.out.println("mouse up");
}
});
setLayout(new BorderLayout());
add(canvas, "Center");
}
}
The delegation model—where a component delegates event handling to another object—doesn't require extending component classes,
which is a much simpler solution. With the delegation event model, event methods return void because events are no longer automatically propagated to a component's container.
The CoR pattern was not applicable for AWT events because GUI events are much too fine-grained; because there are so many events, and components handle them so frequently, the CoR pattern resulted in an explosion of subclasses—an average GUI could easily have upwards of 50 component subclasses for the single purpose of handling events. Finally, propagation of events was rarely used; typically, events are handled by the component in which they originated.
On the other hand, the CoR pattern is a perfect fit for servlet filters. Compared to GUI events, HTTP requests occur infrequently, so the CoR pattern can better handle them. And event propagation is very useful for filters because you can combine them—much like the Unix pipes discussed at the beginning of this article—to produce a myriad of effects.
The Chain of Responsibility pattern lets you decouple an event's sender from its receiver with a chain of objects that are candidates to handle the event. With the classic CoR pattern, one or none of the objects in the chain handles the event; if an object doesn't handle the event, it forwards it to the next object in the chain. In this article, we examined two CoR pattern implementations: the original AWT event model and servlet filters.
Read more about Core Java in JavaWorld's Core Java section.
Archived Discussions (Read only)