- Forward


Advanced Uses of the Observer Pattern in Java
Multicasting, Property Changes, and Other Issues


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

A Common Use of the Oberver Pattern in Java GUIs
Back SMYC Forward
  • Subjects:
    • GUI components (e.g., JButton , JList )
  • Observers:
    • Application-specific classes implement one or more interfaces (e.g., ActionListener , ItemListener )
Creating Subjects of AWT Events
Back SMYC Forward
  • The Situation:
    • You need to create a Component that generates AWT events
  • One Easy Aspect of the Problem:
    • There are many classes that encapsulate AWT events (e.g., ActionEvent , ItemEvent )
  • Complicating Factors:
    • Using the event dispatch thread
    • Maintaining the order of the queue
    • Thread safety
Creating Subjects of AWT Events (cont.)
Back SMYC Forward
  • A Useful Class:
    • AWTEventMulticaster provides efficient and thread-safe message passing to multiple observers
  • Usage:
    • Is a little unusual but straightforward once you understand
Creating Subjects of AWT Events (cont.)
Back SMYC Forward
javaexamples/multicaster/CombinationField.java
 
Creating Subjects of Changes in Object State
Back SMYC Forward
  • The Situation:
    • You have an object that needs to inform observers of changes in its state
  • One Approach:
    • Maintain a collection of observers and send each an appropriate message when state changes
  • Complicating Factors:
    • Maintaining a one-to-one correspondence between state changes and notifications
    • Maintaining the order of the queue
    • Thread safety
Creating Subjects of Changes in Object State (cont.)
Back SMYC Forward
  • A Useful Class:
    • PropertyChangeSupport provides message passing about arbitrary property changes to multiple observers
  • Usage:
    • Straightforward delegation
Creating Subjects of Changes in Object State (cont.)
Back SMYC Forward
A Subject
javaexamples/propertychange/Rectangle.java
 
Creating Subjects of Changes in Object State (cont.)
Back SMYC Forward
An Observer
javaexamples/propertychange/PropertyLabel.java
 
Creating Subjects of Changes in Object State (cont.)
Back SMYC Forward
Usage
javaexamples/propertychange/RectanglePanel.java
 
What About Observer and Observable?
Back SMYC Forward
  • What Were They?
    • Observable was a class that could be extended to create subjects of various kinds
    • Observer was an interface that could be implemented by observers
  • Why Were They Deprecated in v9?
    • Limited event model
    • Unspecified order of notifications
    • State changes not one-to-one with notifications
There's Always More to Learn
Back -