{"id":1445,"date":"2023-04-10T14:14:53","date_gmt":"2023-04-10T07:14:53","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=1445"},"modified":"2024-12-14T23:14:05","modified_gmt":"2024-12-14T16:14:05","slug":"csharp-strategy-pattern","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-strategy-pattern\/","title":{"rendered":"C# Strategy Pattern"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the C# strategy pattern that allows you to change the behavior of an object at runtime.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# strategy pattern<\/h2>\n\n\n\n<p>The strategy design pattern allows you to choose an algorithm from a family of algorithms at runtime by encapsulating each algorithm in a class and making them interchangeable.<\/p>\n\n\n\n<p>The strategy design pattern solves the problem of selecting one algorithm from a set of algorithms based on a condition, without tightly coupling the client code to the selected algorithm.<\/p>\n\n\n\n<p>Suppose you have a program that performs an operation. But there are multiple ways to perform the same operation. <\/p>\n\n\n\n<p>To do that, you can implement each algorithm as a separate method of a class. But that would make the code difficult to maintain and more complex if you want to add more algorithms. In other words, this design doesn&#8217;t conform to the <a href=\"https:\/\/csharptutorial.net\/csharp-design-patterns\/csharp-open-closed-principle\/\">open-closed principle<\/a>. <\/p>\n\n\n\n<p>The strategy pattern solves this problem by allowing you to encapsulate each algorithm in a separate class and make them interchangeable.<\/p>\n\n\n\n<p>The strategy pattern is useful when you want to support different variants of an algorithm. And it is not practical to implement each algorithm as a separate method. <\/p>\n\n\n\n<p>The strategy pattern is also useful when you want to select an algorithm at run time from a set of related algorithms.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Strategy pattern structure<\/h3>\n\n\n\n<p>The following UML diagram illustrates the strategy pattern:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/csharptutorial.net\/wp-content\/uploads\/2023\/04\/CSharp-Strategy-Pattern.svg\" alt=\"\" class=\"wp-image-1523\"\/><\/figure>\n\n\n\n<p>The strategy pattern consists of three main elements:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Context<\/strong>: the class that holds a reference to the strategy object and is responsible for executing the algorithm.<\/li>\n\n\n\n<li><strong>Strategy<\/strong>: the interface that defines the methods which must be implemented by each concrete strategy.<\/li>\n\n\n\n<li><strong>Concrete Strategy<\/strong>: the classes that implement the strategy interface by providing their implementations of the algorithm.<\/li>\n<\/ul>\n\n\n\n<p>In this structure, the context object holds a reference to a strategy object. When the context object needs to perform the algorithm, it delegates the task to the strategy object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Benefits of the strategy pattern<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The strategy pattern allows the client to select the algorithm to use at runtime.<\/li>\n\n\n\n<li>The strategy pattern encapsulates each algorithm in a class, making it easy to modify and extend without affecting the other algorithms.<\/li>\n\n\n\n<li>The strategy pattern decouples the algorithm from the client code, reducing coupling and promoting code reuse.<\/li>\n<\/ul>\n\n\n\n<p>But strategy patterns can increase the complexity of the codebase by adding extra classes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">C# Strategy pattern implementation<\/h2>\n\n\n\n<p>The following example shows an implementation of the strategy pattern in C#:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">StrategyPattern<\/span>;\n\n<span class=\"hljs-comment\">\/\/ Strategy interface<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">interface<\/span> <span class=\"hljs-title\">IStrategy<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Execute<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>;\n}\n\n<span class=\"hljs-comment\">\/\/ Concrete strategy A<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ConcreteStrategyA<\/span> : <span class=\"hljs-title\">IStrategy<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Execute<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        Console.WriteLine(<span class=\"hljs-string\">\"Executing strategy A\"<\/span>);\n    }\n}\n\n<span class=\"hljs-comment\">\/\/ Concrete strategy B<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ConcreteStrategyB<\/span> : <span class=\"hljs-title\">IStrategy<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Execute<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        Console.WriteLine(<span class=\"hljs-string\">\"Executing strategy B\"<\/span>);\n    }\n}\n\n<span class=\"hljs-comment\">\/\/ Context<\/span>\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Context<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> IStrategy? _strategy;\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">SetStrategy<\/span>(<span class=\"hljs-params\">IStrategy strategy<\/span>)<\/span>\n    {\n        _strategy = strategy;\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">ExecuteStrategy<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        _strategy?.Execute();\n    }\n}\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Program<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Main<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>&#91;] args<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> context = <span class=\"hljs-keyword\">new<\/span> Context();\n\n        <span class=\"hljs-comment\">\/\/ Use the strategy A<\/span>\n        context.SetStrategy(<span class=\"hljs-keyword\">new<\/span> ConcreteStrategyA());\n        context.ExecuteStrategy();\n\n        <span class=\"hljs-comment\">\/\/ Use the strategy B<\/span>\n        context.SetStrategy(<span class=\"hljs-keyword\">new<\/span> ConcreteStrategyB());\n        context.ExecuteStrategy();\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Known Uses of the Strategy Pattern in .NET<\/h3>\n\n\n\n<p>The strategy pattern is widely used in .NET, including: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>IComparer<\/code> interface in the <code>System.Collections<\/code> namespace. <\/li>\n\n\n\n<li>The <code>SortedList<\/code> class in the <code>System.Collections.Specialized<\/code> namespace.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The Strategy pattern enables clients to select a specific algorithm from a family of algorithms at runtime, without tightly coupling the client code to the selected algorithm.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1445\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-strategy-pattern\/\"\n\t\t\t\tdata-post-title=\"C# Strategy Pattern\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1445\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-strategy-pattern\/\"\n\t\t\t\tdata-post-title=\"C# Strategy Pattern\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about the C# strategy pattern that allows you to change the behavior of an object at runtime.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1441,"menu_order":10,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1445","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1445","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=1445"}],"version-history":[{"count":5,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1445\/revisions"}],"predecessor-version":[{"id":1609,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1445\/revisions\/1609"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1441"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=1445"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}