Template Method

This lesson discusses how algorithms with multiple steps can be made configurable by allowing subclasses to provide behavior for some of the steps.

What is it ?

A template can be thought of as a general or abstract structure that can be customized for specific situations. You may have used a template for writing your resume. The template would define the overall structure of the document and leave the details to be added in by the template user. The template method pattern is similar, it defines the skeleton or steps of an algorithm but leaves opportunities for subclasses to override some of the steps with their own implementations.

Formally, the pattern is defined as allowing subclasses to define parts of an algorithm without modifying the overall structure of the algorithm.

The template method pattern factors out the common code among its subclasses and puts them into the abstract class. The variable parts of the algorithm are left for the subclasses to override. These parts are template methods. A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior. The ordering of the steps is fixed by the abstract class. Usually, the algorithm is represented as a series of methods which are then invoked in the desired sequence in another method. Note that the classes may choose to ignore overriding certain steps or choose to rely on the default implementation provided by ...