Template Method Pattern

Role

The Template Method pattern enables algorithms to defer certain steps to subclasses. The structure of the algorithm does not change, but small well-defined parts of its operation are handled elsewhere.

Illustration

Consider the sorting algorithms discussed under the Strategy pattern. Each sort has a certain structure that is independent of the kind of items being sorted—except for one operation. At some point, the sort will need to compare two items. The comparison will depend on the types of the items themselves. For example, comparing two integers could be done with a simple i==j, but if the items are, say, People objects, there could be many ways in which they could be compared. If the comparison is done on a Surname field, the sort will yield a list sorted by surname. However, the comparison could also be done on another field, such as Town, which would produce a list of people sorted by the town in which they live. Thus, we can see a clear distinction between the sorting algorithm and some subsidiary operation that is dependent on the data. The same distinction exists for other algorithms, such as searching. Sorting and searching are therefore Template Methods, as some parts of their operation are deferred to other classes.

Design

The UML diagram for the Template Method pattern is given in Figure 7-5. It shows an algorithm class that uses an IPrimitives interface to connect with methods defined in any class. This class would typically handle data ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.