Template method
The Template Method design pattern defines the template of an algorithm as its individual steps. The descendants then implement these steps and represent replaceable algorithms.
Motivation
Several algorithms with the same structure, but with different behavior, may
appear in our application. Saving a document using a specific file format is
often used as an example. File writers for specific file types have different
behavior, but all the documents have the same structure (header, body, and
footer). Therefore, all the writing algorithms consist of the same primitive
operations (WriteHeader()
, WriteBody()
and
WriteFooter()
). The Template Method design pattern utilizes this to
create a unified interface for them.
Pattern
The Template Method pattern implements the skeleton of an algorithm using methods representing its individual steps. These are called primitive operations and are abstract, private methods. The pattern is represented by an abstract class whose descendants then implement specific algorithms.
The algorithms (concrete classes) then have a unified interface (such as
WriteHead()
, WriteBody()
, and
WriteFooter()
), but perform these steps by themselves. This
interface is private, and its called step by step by a public method implemented
in the abstract class (here, it's named TemplateMethod()
). In
practice, it could be named as e.g. Save()
. The descendants will
inherit the method and implement the primitive operations. The problem will be
broken down into subproblems and simplified.
Although these are different algorithms, we get a unified interface that will make the code readable and the further expanding of the system easier.
The number of steps should be as small as possible, and they are
often distinguished by a prefix (e.g. DoWriteHead()
).
The Template Method pattern is basically a subpattern of the Strategy pattern.