The Template Method
This post is a cross-post from www.ModernesCpp.com.
The Template Method is a behavioral design pattern. It defines a skeleton for an algorithm and is probably one of the most often used design patterns from the book "Design Patterns: Elements of Reusable Object-Oriented Software".
The key idea of the Template Method is easy to get. You define the skeleton of an algorithm that consists of a few typical steps. Implementation classes can only override the steps but cannot change the skeleton. The steps are often called hook methods.
Template Method
Purpose
Use case
Structure
AbstractClass
ConcreteClass
Modernes C++ Mentoring
Stay Informed: Subscribe Here.
Example
The following program templateMethod.cpp exemplifies the structure of the Template Method.
// templateMethod.cpp
#include <iostream>
class Sort{
public:
virtual void processData() final { // (4)
readData();
sortData();
writeData();
}
virtual ~Sort() = default;
private:
virtual void readData(){} // (1)
virtual void sortData()= 0; // (2)
virtual void writeData(){} // (3)
};
class QuickSort: public Sort{
void readData() override {
std::cout << "readData" << '\n';
}
void sortData() override {
std::cout << "sortData" << '\n';
}
void writeData() override {
std::cout << "writeData" << '\n';
}
};
class BubbleSort: public Sort{
void sortData() override {
std::cout << "sortData" << '\n';
}
};
int main(){
std::cout << '\n';
QuickSort quick;
Sort* sort = &quick; // (5)
sort->processData();
std::cout << "\n\n";
BubbleSort bubble;
sort = &bubble; // (6)
sort->processData();
std::cout << '\n';
}
Sorting consists of three steps: readData (line 1), sortData (line 2), and writeData (line 3).?The member functions readData() and writeData provide a default implementation, but the member function sortData() is pure virtual. These three steps are the skeleton of the algorithm processData (line 4). Now, quicksort (line 5), and bubble sort (line 6) can be applied.
Here is the output of the program:
I implemented the skeleton function?processData and its three steps as a virtual function. Thanks to the three virtual member functions, late binding kicks in, and the member functions of the run-time object are called. On the contrary, making the skeleton function virtual and declaring it as final, is overkill in C++. final means that a virtual function cannot be overridden.?
When a member function should not be overridable, make it non-virtual.
Non-Virtual Interface (NVI) Idiom
The idiomatic way to implement the Template Method in C++ is to apply the Non-Virtual Interface Idiom. Non-Virtual Interface means that the skeleton is non-virtual, and the steps are virtual. Because the client uses the interface, the skeleton cannot be changed. Here is the corresponding implementation of the interface Sort:
class Sort{
public:
void processData() {
readData();
sortData();
writeData();
}
private:
virtual void readData(){}
virtual void sortData()= 0;
virtual void writeData(){}
};
?
领英推荐
Herb Sutter made the NVI in 2001 popular in C++.?Virtuality.
In his article Virtuality, he boiled the NVI down to four guidelines:
Related Patterns
Pros and Cons
Pros
Cons
What's Next?
Only one pattern from the book "Design Patterns: Elements of Reusable Object-Oriented Software" is missing in my journey: the Strategy Pattern. The Strategy Pattern is heavily used in the Standard Template Library. I will write about the Strategy Pattern in my next post.
?
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dr?ge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschl?ger, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, and Phillip Diekmann.
Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, and Alicja Kaminska.
My special thanks to Embarcadero
My special thanks to PVS-Studio
?
Seminars
I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
Bookable (Online)
German
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
New
Contact Me