In the last episode, we looked at abstracting algorithms.  Now we examine the template method pattern and how it allows us to abstract steps of an algorithm.  Thus, providing a template for implementation while leaving the freedom for subclasses to handle the details.

The Template Method Pattern Defined

As always, we will start with the “Gang of Four” intent to set the stage for our discussion.

“Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.”

This is a rather simple pattern to understand.  We build a root or base class that lays out the steps of an algorithm.  Then we leave some (or all) of those steps to be implemented in subclasses.  Note that we will usually implement some of the steps in the base class to avoid duplication of code.  These steps performed in the base may also provide context and constraints for the subclasses to conform to.

Applying The Pattern

As noted above, most of the time this will start with a base class and some of the steps implemented.  However, that is not a requirement.  You could also start from an interface, but then it may make more sense to stay a little more flexible and use a strategy.  In any case, the concrete part of the implementation will be wrapped up in the subclasses.  This allows you to follow the same steps for the algorithm but do so in varying ways.  A typical application of this pattern is a text processing algorithm that “cleans” data as it goes and has very different work to do in cleaning a date, a street address, or a phone number.  However, this is a pattern that has such a broad number of uses you may easily see it turn up in almost any algorithm.

Java, PHP, C#, etc.

This pattern sticks to the core features of a language.  All you need to implement this is a base class and inheritance.  Therefore, the only differences among languages are going to be minor syntax variations to note what needs to be implemented or overridden in the child classes.

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a longtime student of technology as a developer, designer, and manager of software solutions. Rob is a founder and principle of RB Consulting and has managed to author a book about his family experiences. In his free time, he stays busy raising five children (although a few have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax.

Leave a Reply