Design Patterns Java™ Workbook

(Michael S) #1
Chapter 21. Template Method

Rocket r2 = new Rocket(
"Pocket", 2.95, (Length) METER.times(12));
Rocket r3 = new Rocket(
"Sock-it", 9.95, (Length) METER.times(100));
Rocket r4 = new Rocket(
"Sprocket", 3.95, (Length) METER.times(50));


List rockets =
Arrays.asList(new Rocket[] { r1, r2, r3, r4 });


Comparator c = new Comparator()
{
public int compare(Object o1, Object o2)
{
/? /
}
};


Collections.sort(rockets, c);
Iterator i = rockets.iterator();
while (i.hasNext())
{
System.out.println(i.next());
}
}
}


The program printout depends on how Rocket implements toString() but shows the
rockets sorted by apogee:


Pocket $2.95 (12.0 meters)
Sprocket $3.95 (50.0 meters)
Sock-it $9.95 (100.0 meters)
Mach-it $22.95 (1000.0 meters)


CHALLENGE 21.1


The Rocket class supplies a getApogee()method that returns the height a rocket
can reach. This height is of type Length, a measure whose magnitude you can fetch
with a call to getMagnitude(). Fill in the compare() method in
the ShowComparator program to sort a collection of rockets by apogee.

The sort() method and the Comparator interface let you supply a domain-specific step to
an ancient algorithm. It can also happen that the entire algorithm is domain specific.


Completing an Algorithm..........................................................................................................................


As in the ADAPTER pattern, a thoughtful developer may foresee that you have a role in
completing his or her design. In ADAPTER, you supply an object that responds to the needs of
the other developer's code. In TEMPLATE METHOD, you supply a step of an algorithm.


Consider the Aster star press that Figure 21.2 shows. A star press from Aster Corporation
accepts empty metal molds and presses fireworks stars into them. The machine has hoppers,

Free download pdf