Java Reference
In-Depth Information
Chapter 21. Template Method
In a sense, almost every method is a template. Ordinary methods have bodies that define
a sequence of instructions. It is also quite ordinary for a method to invoke methods on
the current object and on other objects. Ordinary methods are, in this sense, "templates" that
merely outline a series of instructions for the computer to follow. The T EMPLATE M ETHOD
pattern, however, involves a more specific type of template.
When you write a method, you may want to define the outline of an algorithm, understanding
that there may be differences in how you want to implement certain steps. In this case, you
can define the method but leave some steps as abstract methods, as stubbed-out methods, or as
methods defined in a separate interface. This produces a more rigid "template" that
specifically defines which steps of an algorithm other classes can or must supply. The intent
of T EMPLATE M ETHOD is to implement an algorithm in a method, deferring the definition of
some steps of the algorithm so that other classes can redefine them.
A Classic Example of Template Method: Sorting
An ancient example of T EMPLATE M ETHOD that is not only pre-Java but also prehistoric
occurs in sorting. 1 Sorting has various algorithms, but in most settings, you can establish a
single algorithm and use it to sort various collections of objects. Any algorithm that you use
for sorting will rely on the primitive step of comparing two items, or attributes. If you can
compare, say, the sharpness of two arrowheads, your sorting algorithm will let you sort the
arrowheads in a collection.
In recent times, sorting probably reigns as the most frequently reimplemented algorithm, with
implementations outnumbering the number of existing computer programmers. But unless
you are sorting a huge collection, you need not write your own sorting algorithm.
The Collections class in java.util , shown in Figure 21.1, provides a sorting algorithm
as a T EMPLATE M ETHOD , deferring the comparison step to you.
1 Some developers think of sorting as an example of S TRATEGY . Challenge 23.6 on page 247 will ask you to
compare S TRATEGY and T EMPLATE M ETHOD .
Search WWH ::




Custom Search