{"id":6489,"date":"2022-12-04T17:02:44","date_gmt":"2022-12-04T17:02:44","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/the-template-method\/"},"modified":"2022-12-04T17:02:44","modified_gmt":"2022-12-04T17:02:44","slug":"the-template-method","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/the-template-method\/","title":{"rendered":"The Template Method"},"content":{"rendered":"<p>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 &#8220;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software&#8221;<\/a>.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6479\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern.png\" alt=\"BehavioralPattern\" width=\"650\" height=\"329\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern.png 1234w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-300x152.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-1024x518.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-768x388.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/p>\n<p>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.<\/p>\n<h2>Template Method<\/h2>\n<h3>Purpose<\/h3>\n<ul>\n<li>Define a skeleton of&nbsp; an algorithm consisting of a few typical steps<\/li>\n<li>Subclasses can adjust the steps but not the skeleton<\/li>\n<\/ul>\n<h3>Use case<\/h3>\n<ul>\n<li>Different variants of an algorithm should be used<\/li>\n<li>The variants of an algorithm consist of similar steps<\/li>\n<\/ul>\n<h3>Structure<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6487\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/TemplateMethodGraphic.png\" alt=\"TemplateMethodGraphic\" width=\"400\" height=\"278\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/TemplateMethodGraphic.png 329w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/TemplateMethodGraphic-300x209.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p><strong><code>AbstractClass<\/code><\/strong><\/p>\n<ul>\n<li>Defines the structure of the algorithm, consisting of various steps<\/li>\n<li>The steps of the algorithm can be virtual or pure virtual<\/li>\n<\/ul>\n<p><strong><code>ConcreteClass<\/code><\/strong><\/p>\n<ul>\n<li>Overwrites the specific steps of the algorithm if necessary<\/li>\n<\/ul>\n<h3>Example<\/h3>\n<p>The following program <code>templateMethod.cpp<\/code> exemplifies the structure of the Template Method.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ templateMethod.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Sort<\/span>{\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> processData() final { <em><span style=\"color: #0099ff;\">\/\/ (4)<\/span><\/em>\r\n        readData();             \r\n        sortData();\r\n        writeData();\r\n    }<br \/>    <strong><span style=\"color: #006699;\">virtual<\/span><\/strong> ~Sort() = default;\r\n<span style=\"color: #9999ff;\">private:<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> readData(){}        <em><span style=\"color: #0099ff;\">\/\/ (1) <\/span><\/em> \r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> sortData()<span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;      <em><span style=\"color: #0099ff;\">\/\/ (2)<\/span><\/em>\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeData<\/span>(){}       <em><span style=\"color: #0099ff;\">\/\/ (3)<\/span><\/em>\r\n};\r\n\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">QuickSort<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Sort{\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> readData() override {\r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"readData\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n    }\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> sortData() override {\r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span>  <span style=\"color: #cc3300;\">\"sortData\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n    }\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeData() override {\r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"writeData\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n    }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">BubbleSort<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Sort{\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> sortData() override {\r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span>  <span style=\"color: #cc3300;\">\"sortData\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n    }\r\n};\r\n\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\r\n    QuickSort quick;\r\n    Sort<span style=\"color: #555555;\">*<\/span> sort <span style=\"color: #555555;\">=<\/span> <span style=\"color: #555555;\">&amp;<\/span>quick;          <em><span style=\"color: #0099ff;\">\/\/ (5)<\/span><\/em>\r\n    sort<span style=\"color: #555555;\">-&gt;<\/span>processData();\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n\r\n    BubbleSort bubble;\r\n    sort <span style=\"color: #555555;\">=<\/span> <span style=\"color: #555555;\">&amp;<\/span>bubble;               <em><span style=\"color: #0099ff;\">\/\/ (6)<\/span><\/em>\r\n    sort<span style=\"color: #555555;\">-&gt;<\/span>processData();\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n  \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Sorting consists of three steps: <code>readData<\/code> (line 1), <code>sortData <\/code>(line 2), and <code>writeData<\/code> (line 3).&nbsp; The member functions <code>readData()<\/code> and <code>writeData<\/code> provide a default implementation, but the member function <code>sortData()<\/code> is pure virtual. These three steps are the skeleton of the algorithm <code>processData <\/code>(line 4). Now, quicksort (line 5), and bubble sort (line 6) can be applied.<\/p>\n<p>Here is the output of the program:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6488\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/templateMethod.png\" alt=\"templateMethod\" width=\"350\" height=\"233\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/templateMethod.png 805w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/templateMethod-300x200.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/templateMethod-768x511.png 768w\" sizes=\"auto, (max-width: 350px) 100vw, 350px\" \/><\/p>\n<p>I implemented the skeleton function&nbsp;<code>processData<\/code> 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 <code>final<\/code>, is overkill in C++. <code>final<\/code> means that a virtual function cannot be overridden.&nbsp;<\/p>\n<p>When a member function should not be overridable, make it non-virtual.<\/p>\n<h4>Non-Virtual Interface (NVI) Idiom<\/h4>\n<p>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 <code>Sort<\/code>: <code><br \/><\/code><\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Sort<\/span>{\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> processData() {\r\n        readData();\r\n        sortData();\r\n        writeData();\r\n    }\r\n<span style=\"color: #9999ff;\">private:<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> readData(){}\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> sortData()<span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeData<\/span>(){}\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Herb Sutter made the NVI in 2001 popular in C++.&nbsp; <a href=\"http:\/\/www.gotw.ca\/publications\/mill18.htm\">Virtuality<\/a>.<\/p>\n<p>In his article <a href=\"http:\/\/www.gotw.ca\/publications\/mill18.htm\">Virtuality<\/a>, he boiled the NVI down to four guidelines:<\/p>\n<ul>\n<li><em>Guideline #1: Prefer to make interfaces nonvirtual, using Template Method design pattern.<\/em><\/li>\n<li><em>Guideline #2: Prefer to make virtual functions private.<\/em><\/li>\n<li><em>Guideline #3: Only if derived classes need to invoke the base implementation of a virtual function, make the virtual function protected.<\/em><\/li>\n<li><em>Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.<\/em><\/li>\n<\/ul>\n<h3>Related Patterns<\/h3>\n<ul>\n<li>The Template Method and Strategy Pattern use cases are pretty similar. Both patterns enable it to provide variations of an algorithm. The Template Method is based on a class level by subclassing, and the Strategy Pattern on an object level by composition. The Strategy Pattern gets is various strategies as objects and can, therefore, exchange its strategies at run time. The Template Method inverts the control flow, following the <a href=\"https:\/\/wiki.c2.com\/?HollywoodPrinciple\"><em>Hollywood principle<\/em><\/a>: &#8220;Don&#8217;t call us, we call you. The Strategy Pattern is often a black box. It allows you to replace one strategy with another without knowing its details.<\/li>\n<li>The<a href=\"https:\/\/en.wikipedia.org\/wiki\/Factory_method_pattern\"> Factory Method<\/a> is often called in specific steps of the Template Method.<\/li>\n<\/ul>\n<h3>Pros and Cons<\/h3>\n<h4>Pros<\/h4>\n<ul>\n<li>New variations of an algorithm are easy to implement by creating new subclasses<\/li>\n<li>Common steps of the algorithms can be implemented directly in the interface class<\/li>\n<\/ul>\n<h4>Cons<\/h4>\n<ul>\n<li>Now, even small variations of an algorithm require the creation of a new class; this may lead to the creation of many small classes<\/li>\n<li>The skeleton is fixed and cannot be changed; you can overcome this limitation by making the skeleton function virtual<\/li>\n<\/ul>\n<h2>What&#8217;s Next?<\/h2>\n<p>Only one pattern from the book &#8220;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software&#8221;<\/a> is missing in my journey: the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Strategy_pattern\">Strategy Pattern<\/a>. The Strategy Pattern is heavily used in the Standard Template Library. I will write about the Strategy Pattern in my next post.<\/p>\n<p>&nbsp;<\/p>\n<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &#8220;Design Patterns: Elements of Reusable Object-Oriented Software&#8221;.<\/p>\n","protected":false},"author":21,"featured_media":6479,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[379],"tags":[],"class_list":["post-6489","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-patterns"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6489","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=6489"}],"version-history":[{"count":0,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6489\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/6479"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=6489"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6489"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6489"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}