Black Friday Black Friday
Black Friday ultimate sale! Get up to 80 % extra free points! More information here

Template method

Software design Design patterns GOF Behavioral Patterns 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

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.


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
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 College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
Strategy
Thumbnail
All articles in this section
GOF - Behavioral Patterns
Thumbnail
Next article
State
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!