21 Template Method

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. In this sense, ordinary methods are “templates” that outline a series of instructions for the computer to follow. The TEMPLATE METHOD pattern, however, involves a more specific type of template.

When you write a method, you may want to define the outline of an algorithm while allowing for the fact 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” ...

Get Design Patterns in Java™, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.