Design Patterns Java™ Workbook

(Michael S) #1
Chapter 9. Observer

CHALLENGE 9.1


Complete the slider() and stateChanged() methods for
ShowBallistics_1 so that the ballistics panels and the tpeak label reflect
the slider's value.

public JSlider slider()
{
if (slider == null)
{
slider = new JSlider();
sliderMax = slider.getMaximum();
sliderMin = slider.getMinimum();
slider.addChangeListener( ?? );
slider.setValue(slider.getMinimum());
}
return slider;
}

public void stateChanged(ChangeEvent e)
{
double val = slider.getValue();
double tp = (val - sliderMin) / (sliderMax - sliderMin);
burnPanel().?? ( ?? );
thrustPanel().?? ( ?? );
valueLabel().?? ( ?? );
}

The ShowBallistics_1 class updates the burn panel, thrust panel, and value label objects
that depend on the slider's value. This is not uncommon and not necessarily bad code, but
note: This code completely undoes the intent of OBSERVER! Swing applies OBSERVER so that
the slider is not responsible for knowing which clients are interested in it.
The ShowBallistics_1 code registers a single dependent object—itself—that dispatches
changes to interested objects. This object takes on responsibility for knowing which clients
depend on the slider, instead of letting each dependent object register itself.


To be consistent with OBSERVER, you can make a few changes in the code to let each
interested component register itself to receive the slider's change events.


CHALLENGE 9.2


Provide a new class diagram showing a design that lets each interested object
register for slider events. Be sure to account for the label that shows the slider's
value.

In this design, you can move the calls to addChangeListener() out of the slider()
method and into the constructors of the dependent components:

Free download pdf