Template Design Pattern

COMP 310  Java Resources  Eclipse Resources

(Back to Design Patterns)

Summary: Illustrates and explains the workings of the template design pattern.

Template Design Pattern

The Template Design Pattern is perhaps one of the most widely used and useful design pattern. It is used to set up the outline or skeleton of an algorithm, leaving the details to specific implementations later. This way, subclasses can override parts of the algorithm without changing its overall structure.

This is particularly useful for separating the variant and the invariant behavior, minimizing the amount of code to be written. The invariant behavior is placed in the abstract class (template) and then any subclasses that inherit it can override the abstract methods and implement the specifics needed in that context. In the body of TemplateMethod() (see UML diagram below), there are calls to operation1() and operation2(). What it is that operation1() and operation2() do are defined by the subclasses which override them.

Figure 1: The Template design pattern in action: a template class and two subclasses of it.
Template Design Pattern
Template Design Pattern (template.png)

A common example of this is when writing a program that will handle data using various sorting algorithms. The AbstractClass would have a method called Sort() (analogous to TemplateMethod() — the invariant behavior) which when called, would use the helper methods in the class, which are specified by any class that inherits from it. The helper methods in this case might be compare() (compares two objects and returns the one that is "higher") and sortPass() (performs one iteration of a particular sorting algorithm) The interesting thing is that the usual control structure of object calls and relations is reversed. It is the parent class that calls the method in the subclass, a behavior which Richard E. Sweet refers to as the "Hollywood Principle" — "Don't call us, we'll call you." The Template Design Pattern is of particular use in the Factory Design Pattern.

 

 


Originally published in Connexions (CNX): https://web.archive.org/web/20140429094723/https://cnx.org/content/m17188/latest/

© 2023 by Stephen Wong