Get up to 80 % extra points for free! More info:

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 Template Method design pattern – UML diagram - GOF - Behavioral Patterns

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.


 

All articles in this section
GOF - Behavioral Patterns
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities