Using Interfaces for Callbacks
Limitations of Measurable interface:
Can add Measurable interface only to classes under your control
Can measure an object in only one way
E.g., cannot analyze a set of savings accounts both by bank balance and by
interest rate
Callback mechanism: allows a class to call back a specific method when it needs more information
In previous DataSet implementation, responsibility of measuring lies with the added objects themselves
Alternative: Hand the object to be measured to a method:
public interface Measurer
{
double measure(Object anObject);
}
Object is the "lowest common denominator" of all classes
add
method asks
measurer (and
not the added object) to do the measuring:
public void
add(Object x)
{
sum = sum +
measurer.measure(x);
if (count == 0 ||
measurer.measure(maximum)
<
measurer.measure(x))
maximum = x;
count++;
}
You can define
measurers to take on any kind of measurement
public class
RectangleMeasurer
implements Measurer
{
public double measure(Object anObject)
{
Rectangle aRectangle = (Rectangle) anObject;
double area = aRectangle.getWidth() * aRectangle.getHeight();
return area;
}
}
Must cast from
Object
to
Rectangle
Rectangle aRectangle =
(Rectangle)
anObject;
Pass measurer to data set constructor:
Measurer m = new RectangleMeasurer();
DataSet data = new DataSet(m);
data.add(new Rectangle(5, 10, 20, 30));
data.add(new Rectangle(10, 20, 30, 40)); . . .
Note that the Rectangle class is decoupled from the Measurer interface
Click here for Example of Measurer Interface.
Suppose you want to use the DataSet class of Section 9.1 to find the longest String from a set of inputs. Why can't this work?
Answer: The String class doesn't implement the Measurable interface.
Why does the measure method of the Measurer interface have one more parameter than the getMeasure method of the Measurable interface?
Answer: A measurer measures an object, whereas getMeasure measures "itself", that is, the implicit parameter.