Java Reference
In-Depth Information
CHALLENGE 21.4
Suppose that you provide the Machine class with a planner attribute of type
MachinePlanner and delete the existing getPlanner() methods in
the subclasses. Write the code for getPlanner() in the Machine class.
You can often refactor your code into an instance of T EMPLATE M ETHOD . You do so by
abstracting the outline of the similar methods, moving the outline method up to a superclass,
and letting subclasses supply just the step where they differ in their implementation of the
algorithm.
Summary
Ordinary methods are usually templates in that you can't tell exactly what code will execute
just by looking at a single method. The T EMPLATE M ETHOD pattern, however, does not
merely note that ordinary methods are templates. Rather, the intent of T EMPLATE M ETHOD is
to define an algorithm in a method, leaving some steps abstract, stubbed out, or defined in
an interface so that other classes can fill them in.
T EMPLATE M ETHOD often functions as a contract between developers. One developer
supplies the outline of an algorithm, and another developer supplies a certain step of
the algorithm. This may be a step that lets the algorithm complete, or it may be a step that
the algorithm developer includes to hook in your code at specific points in the procedure.
The intent of T EMPLATE M ETHOD does not imply that you will always write the template
method in advance of defining subclasses. You may discover similar methods in an existing
hierarchy. In this case, you may be able to distill the outline of an algorithm and move it up to
a superclass, applying T EMPLATE M ETHOD to simplify and to organize your code.
Search WWH ::




Custom Search