Member-only story
Design Patterns: Template Method
A complex pattern explained using Pokemon

There are 23 classic design patterns, which are described in the original book, Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems, often repeated in software development.
In this article, I’m going to describe the template pattern, and how and when it should be applied.
Template Method Pattern: Basic Idea
“The template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses” — Wikipedia
“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. “— Design Patterns: Elements of Reusable Object-Oriented Software
The main feature of this pattern is an algorithm which changes slightly between different kinds of classes. These parts commonly are repeated in the different algorithms when implemented in a concrete class.
The following code shows the classic problem where you must repeat parts of an algorithm (copy-paste), with very small changes:

We can make this code a lot cleaner by using the template method pattern, which allows us to avoid repeating code in the different implementations of the algorithm. The UML diagram of this pattern is the following:

Note the abstract class, containing the template method and the private methods in common.
The template method describes the algorithm in different steps. The steps are implemented in the abstract class, while the concrete steps, different in each concrete class, are implemented in said concrete class.