Template Design Pattern



The Template Design Pattern 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 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.

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, a behaviour 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.


Leave a Comment

You must be logged in to post a comment.