Template Design Pattern

Template Design Pattern is one of the most widely and frequently used design pattern which is based on behavior which Richard E. Sweet refers to as the “Hollywood Principle” — “Don’t call us, we’ll call you.”. In this pattern, subclasses can override parts of the algorithm without changing its overall structure.

This is particularly useful for separating the variant and the invariant behaviour, minimizing the amount of code to be written. The invariant behaviour 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.

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() (analagous to TemplateMethod() — the invariant behaviour) 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.

 Read Singleton Pattern