{"id":6492,"date":"2022-11-12T20:17:37","date_gmt":"2022-11-12T20:17:37","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/the-strategy-pattern\/"},"modified":"2023-06-26T08:54:29","modified_gmt":"2023-06-26T08:54:29","slug":"the-strategy-pattern","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/the-strategy-pattern\/","title":{"rendered":"The Strategy Pattern"},"content":{"rendered":"<p>The Strategy Pattern is a behavioral design pattern from the book <a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software&#8221;<\/a>. It defines a family of algorithms and encapsulates them in objects.<\/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 Strategy Pattern is heavily used in the Standard Template Library.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_Strategy_Pattern\"><\/span>The Strategy Pattern<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Purpose\"><\/span>Purpose<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>Defines a family of algorithms and encapsulates them in objects<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Also_known_as\"><\/span>Also known as<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>Policy<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Use_case\"><\/span>Use case<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>Different variations of an algorithm are needed<\/li>\n<li>The client does not need to know the algorithm<\/li>\n<li>The algorithm should be exchangeable at the run time of a program<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"_Structure\"><\/span>&nbsp;Structure<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6422\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/08\/Strategy.png\" alt=\"Strategy\" width=\"332\" height=\"215\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/08\/Strategy.png 332w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/08\/Strategy-300x194.png 300w\" sizes=\"auto, (max-width: 332px) 100vw, 332px\" \/><\/p>\n<p><strong><code>Strategy<\/code><\/strong><\/p>\n<ul>\n<li>Defines the interface for the family of algorithms<\/li>\n<\/ul>\n<p><strong><code>ConcreteStrategy<\/code><\/strong><\/p>\n<ul>\n<li>Implements an algorithm<\/li>\n<\/ul>\n<p><strong><code>Context<\/code><\/strong><\/p>\n<ul>\n<li>Manages a reference to a <code>ConcreteStrategy<\/code><\/li>\n<li>Has a <code>ConcreteStrategy<\/code><\/li>\n<\/ul>\n<p>The <code>Context<\/code> has a <code>ConcreteStrategy<\/code> that is encapsulated in an object. The <code>ConcreteStrategy<\/code> implements the interface of <code>Strategy<\/code>. Typically, the <code>ConcreteStrategy<\/code> can be adjusted during run time.<\/p>\n<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Example\"><\/span>Example<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The following example <code>strategy.cpp<\/code> uses three concrete strategies and follows the naming conventions in the previous image.<\/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;\">\/\/ strategy.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;memory&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;utility&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Strategy<\/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> execute() <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;                           <em><span style=\"color: #0099ff;\">\/\/ (4)<\/span><\/em>\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #555555;\">~<\/span>Strategy() {}\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Context<\/span> {\r\n    std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Strategy<span style=\"color: #555555;\">&gt;<\/span> strat{};                    <span style=\"color: #0099ff;\"><em>\/\/ (1)<\/em><\/span>\r\n<span style=\"color: #9999ff;\">public:                                                   <\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">setStrategy<\/span>(std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Strategy<span style=\"color: #555555;\">&gt;<\/span> strat_)  {<span style=\"color: #0099ff;\"><em> \/\/ (2)<\/em><\/span><br \/>        strat <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>move(strat_); }<br \/>    }\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">strategy<\/span>()  { <span style=\"color: #006699; font-weight: bold;\">if<\/span> (strat) strat<span style=\"color: #555555;\">-&gt;<\/span>execute(); }     <span style=\"color: #0099ff;\"><em>\/\/ (3)<\/em>\r\n};<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Strategy1<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Strategy {\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> execute() { std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Strategy1 executed<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>; }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Strategy2<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Strategy {\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> execute() { std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Strategy2 executed<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>; }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Strategy3<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Strategy {\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> execute() { std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Strategy3 executed<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>; }\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    Context k;\r\n\r\n    k.setStrategy(std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>Strategy1<span style=\"color: #555555;\">&gt;<\/span>());\r\n    k.strategy();\r\n\r\n    k.setStrategy(std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>Strategy2<span style=\"color: #555555;\">&gt;<\/span>());\r\n    k.strategy();\r\n\r\n    k.setStrategy(std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>Strategy3<span style=\"color: #555555;\">&gt;<\/span>());\r\n    k.strategy();\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><code>Context<\/code> has a strategy (line 1) that can be set (line 2) and can be executed (line 3). Each strategy has to support the member function <code>execute<\/code> (line 4).&nbsp; The <code>main<\/code> program uses three concrete strategies, sets them, and executes them. Here is the output of the program.<\/p>\n<h3><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6491\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/strategyExample.png\" alt=\"strategyExample\" width=\"406\" height=\"265\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/strategyExample.png 406w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/strategyExample-300x196.png 300w\" sizes=\"auto, (max-width: 406px) 100vw, 406px\" \/><\/h3>\n<h3><span class=\"ez-toc-section\" id=\"Usage_in_C\"><\/span>Usage in C++<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The Strategy Pattern is heavily used in the Standard Template Library. In the case of templates, we call it Policy.<\/p>\n<p>A policy is a generic function or class whose behavior can be configured. Typically, there are default values for the policy parameters.<code> std::vector<\/code> and<code> std::unordered_map<\/code> exemplifies policies in C++.<\/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;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">T<\/span>, <span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Allocator<\/span> <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>allocator<span style=\"color: #555555;\">&lt;<\/span>T<span style=\"color: #555555;\">&gt;&gt;<\/span>          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">vector<\/span>; \r\n\r\n<span style=\"color: #006699; font-weight: bold;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Key<\/span>,\r\n    <span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">T<\/span>,\r\n    <span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Hash<\/span> <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>hash<span style=\"color: #555555;\">&lt;<\/span>Key<span style=\"color: #555555;\">&gt;<\/span>,                               <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">KeyEqual<\/span> <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>equal_to<span style=\"color: #555555;\">&lt;<\/span>Key<span style=\"color: #555555;\">&gt;<\/span>,                       <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">allocator<\/span> <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>allocator<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>pair<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">const<\/span> Key, T<span style=\"color: #555555;\">&gt;&gt;<\/span>  <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">unordered_map<\/span>;\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>This means each container has a default allocator for its elements depending on T (line 1) or on <code>std::pair&lt;const Key, T&gt;<\/code> (line 2). Additionally,<code> std::unorderd_map<\/code> has a default hash function (line 3) and a default equal function (4). The hash function calculates the hash value based on the key, and the equal function deals with collisions in the buckets. My previous post &#8220;<a href=\"https:\/\/www.modernescpp.com\/index.php\/hash-functions\">Hash Functions<\/a>&#8221; gives you more information about<code> std::unordered_map<\/code>.<\/p>\n<p>Consequentially, you can use a user-defined data type such as <code>MyInt<\/code> as a key in a<code> std::unordered_map<\/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: #0099ff; font-style: italic;\">\/\/ templatesPolicy.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;unordered_map&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MyInt{\r\n    <span style=\"color: #006699; font-weight: bold;\">explicit<\/span> MyInt(<span style=\"color: #007788; font-weight: bold;\">int<\/span> v)<span style=\"color: #555555;\">:<\/span>val(v){}\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> val;\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MyHash{                                                        <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span><span style=\"color: #007788; font-weight: bold;\">size_t<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span>()(MyInt m) <span style=\"color: #006699; font-weight: bold;\">const<\/span> {\r\n        std<span style=\"color: #555555;\">::<\/span>hash<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span> hashVal;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #cc00ff;\">hashVal<\/span>(m.val);\r\n    }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MyEqual{\r\n    <span style=\"color: #007788; font-weight: bold;\">bool<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span> () (<span style=\"color: #006699; font-weight: bold;\">const<\/span> MyInt<span style=\"color: #555555;\">&amp;<\/span> fir, <span style=\"color: #006699; font-weight: bold;\">const<\/span> MyInt<span style=\"color: #555555;\">&amp;<\/span> sec) <span style=\"color: #006699; font-weight: bold;\">const<\/span> {      <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> fir.val <span style=\"color: #555555;\">==<\/span> sec.val;\r\n    }\r\n};\r\n\r\nstd<span style=\"color: #555555;\">::<\/span>ostream<span style=\"color: #555555;\">&amp;<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> (std<span style=\"color: #555555;\">::<\/span>ostream<span style=\"color: #555555;\">&amp;<\/span> strm, <span style=\"color: #006699; font-weight: bold;\">const<\/span> MyInt<span style=\"color: #555555;\">&amp;<\/span> myIn){     <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    strm <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"MyInt(\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> myIn.val <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\")\"<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> strm;\r\n}\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> main(){\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    <span style=\"color: #006699; font-weight: bold;\">using<\/span> MyIntMap <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>unordered_map<span style=\"color: #555555;\">&lt;<\/span>MyInt, <span style=\"color: #007788; font-weight: bold;\">int<\/span>, MyHash, MyEqual<span style=\"color: #555555;\">&gt;<\/span>;  <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4)<\/span>\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"MyIntMap: \"<\/span>;\r\n    MyIntMap myMap{{MyInt(<span style=\"color: #555555;\">-<\/span><span style=\"color: #ff6600;\">2<\/span>), <span style=\"color: #555555;\">-<\/span><span style=\"color: #ff6600;\">2<\/span>}, {MyInt(<span style=\"color: #555555;\">-<\/span><span style=\"color: #ff6600;\">1<\/span>), <span style=\"color: #555555;\">-<\/span><span style=\"color: #ff6600;\">1<\/span>}, {MyInt(<span style=\"color: #ff6600;\">0<\/span>), <span style=\"color: #ff6600;\">0<\/span>}, {MyInt(<span style=\"color: #ff6600;\">1<\/span>), <span style=\"color: #ff6600;\">1<\/span>}};\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span>(<span style=\"color: #006699; font-weight: bold;\">auto<\/span> m <span style=\"color: #555555;\">:<\/span> myMap) std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'{'<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> m.first <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\", \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> m.second <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"}\"<\/span>;\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}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I implemented the hash function (line 1), and the equal function (line 2) as a function object and overloaded, for convenience reasons, the output operator (line 3). Line 4 creates out of all components a new type MyIntMap, that uses <code>MyInt<\/code> as a <code>key<\/code>. The following screenshot shows the output of the instance <code>myMap<\/code>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6322\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/03\/templatesPolicy.png\" alt=\"templatesPolicy\" width=\"500\" height=\"161\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/03\/templatesPolicy.png 681w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/03\/templatesPolicy-300x97.png 300w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<h3><span class=\"ez-toc-section\" id=\"Related_Patterns\"><\/span>Related Patterns<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Template_method_pattern\">Template Method<\/a> 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 will call you&#8221;. 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\/Bridge_pattern\">Bridge Pattern <\/a>and the Strategy Pattern have identical structures but different intents. The Bridge Pattern is a structural pattern and aims to decouple physical dependencies, the Strategy Pattern is a behavioral pattern that decouples logical dependencies and allows to injection of external implementations.<\/li>\n<\/ul>\n<p>Let&#8217;s talk about the pros and cons of the Strategy Pattern.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Pros_and_Cons\"><\/span>Pros and Cons<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<h4>Pros<\/h4>\n<ul>\n<li>Algorithms are encapsulated in objects and can be exchanged during run time<\/li>\n<li>Adding new strategies is easy. You only have to implement a new strategy.<\/li>\n<li>The Strategy Pattern replaces conditional execution based on<code> if\/else<\/code> statements or <code>switch<\/code> statements<\/li>\n<li>Callables are often lightweight implementations for strategies in C++:<\/li>\n<\/ul>\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: #0099ff; font-style: italic;\">\/\/ sortVariations.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;algorithm&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;string&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;vector&gt;<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">bool<\/span> <span style=\"color: #cc00ff;\">greater<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> first, <span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> second) {\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> first <span style=\"color: #555555;\">&gt;<\/span> second;\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>vector<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&gt;<\/span> myStrings{<span style=\"color: #cc3300;\">\"Only\"<\/span>, <span style=\"color: #cc3300;\">\"for\"<\/span>, <span style=\"color: #cc3300;\">\"testing\"<\/span>, <span style=\"color: #cc3300;\">\"purpose\"<\/span>, <span style=\"color: #cc3300;\">\".\"<\/span>};\r\n\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ sort ascending<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrings.begin(), myStrings.end());\r\n\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ sort descending                           \/\/ (1)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrings.begin(), myStrings.end(), greater);\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrings.begin(), myStrings.end(), std<span style=\"color: #555555;\">::<\/span>greater<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&gt;<\/span>());\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrings.begin(), myStrings.end(), [](<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> first, <span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> second) {\r\n                                                      <span style=\"color: #006699; font-weight: bold;\">return<\/span> first <span style=\"color: #555555;\">&gt;<\/span> second; \r\n                                                    });\r\n\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ sort based on the length of the strings<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrings.begin(), myStrings.end(), [](<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> first, <span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> second) {\r\n                                                      <span style=\"color: #006699; font-weight: bold;\">return<\/span> first.length() <span style=\"color: #555555;\">&lt;<\/span> second.length(); \r\n                                                    });\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The program uses the function <code>greater<\/code>, the predefined function object<code> std::greater&lt;std::string&gt;<\/code>, and a lambda expression (line 1) to sort a <code>std::vector&lt;std::string<\/code>&gt; in descending way. The callables are, in this example, binary predicates.<\/p>\n<h4>Cons<\/h4>\n<ul>\n<li>Clients must know and choose the right strategy<\/li>\n<li>The number of objects (strategies) increases heavily<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Whats_Next\"><\/span>What&#8217;s Next?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>I presented in my last posts the following Design Patterns from the seminal book &#8220;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software<\/a>&#8220;.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6386\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/06\/15DesignPattern.jpg\" alt=\"15DesignPattern\" width=\"600\" height=\"260\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/06\/15DesignPattern.jpg 807w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/06\/15DesignPattern-300x130.jpg 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/06\/15DesignPattern-768x333.jpg 768w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>The ones listed here are the ones most relevant in my past. In my next post, I will write about idioms in C++. An idiom is an implementation of an architecture or design pattern in a concrete programming language.<\/p>\n<p>&nbsp;<\/p>\n<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Strategy Pattern is a behavioral design pattern from the book Design Patterns: Elements of Reusable Object-Oriented Software&#8221;. It defines a family of algorithms and encapsulates them in objects.<\/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":[402],"class_list":["post-6492","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-patterns","tag-policy"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6492","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=6492"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6492\/revisions"}],"predecessor-version":[{"id":6654,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6492\/revisions\/6654"}],"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=6492"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6492"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6492"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}