Java Reference
In-Depth Information
The observer pattern encapsulates a simple but powerful concept that can greatly extend your
programs. The observer pattern isn't implemented by using java.util.Observable class and
java.util.Observer in many real‐life cases, but rather is implemented in the form of a hand‐
rolled approach where one class keeps a list of objects it needs to “notify” in some way whenever
something interesting happens. The reasons for this stem mainly from the fact that programmers
sometimes want to get creative with their use of notification methods, want to keep a list of multiple
types of observers, or are hindered by the fact that Observable is an abstract class that needs to
be extended, preventing classes from extending from another abstract class. Don't worry, though,
the pattern and the basic idea behind it are the same.
In fact, it seems that many built‐in parts of Java are hampered by this issue, since many classes
(especially those dealing with GUIs) prefer to go for a hand‐rolled approach. In the Java world,
people often refer to the observer pattern as the listener pattern (observers are called listeners in that
case). The basic pattern is like this:
The subject class keeps a list of registered listeners and is free to extend its own abstract
classes.
The listeners all implement an interface defining the “notification” methods.
When something interesting happens to the subject, it goes through its list of listeners and
calls the appropriate notification method.
A perfect way to illustrate this is by building a simple GUI application. As the subject, a simple
JFrame is used here:
import javax.swing.JFrame;
public class GUIListenerExample {
public static void main(String[] args) {
// Create our subject
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create our listener
MyMouseListener listener = new MyMouseListener();
// Register
frame.addMouseListener(listener);
// Go
frame.setVisible(true);
}
}
Note that javax.swing.JFrame extends java.awt.Frame and thus has nothing to do with
Observable . The listener is created as follows:
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JOptionPane;
Search WWH ::




Custom Search