{"id":1528,"date":"2023-04-11T17:10:15","date_gmt":"2023-04-11T10:10:15","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=1528"},"modified":"2024-12-14T23:05:09","modified_gmt":"2024-12-14T16:05:09","slug":"csharp-factory-method","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-factory-method\/","title":{"rendered":"C# Factory Method"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the C# factory method design pattern and how to use it to create objects without tightly coupling the object creation code to the client code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# factory method design pattern<\/h2>\n\n\n\n<p>A real-world factory produces products. In programming, a factory creates objects. When a method creates and returns an object, it is called a factory method.<\/p>\n\n\n\n<p>The Factory Method pattern is a creational design pattern, which provides an <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-interface\/\">interface<\/a> for creating objects in a superclass but allows subclasses to decide the object type.<\/p>\n\n\n\n<p>The following UML diagram illustrates the Factory Method pattern:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/csharptutorial.net\/wp-content\/uploads\/2023\/04\/csharp-factory-method-design-pattern.svg\" alt=\"C# factory method design pattern\" class=\"wp-image-1530\"\/><\/figure>\n<\/div>\n\n\n<p>The Factory Method pattern consists of the following participants:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>Creator<\/code>: the <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-abstract-class\/\">abstract class<\/a> that defines a factory method for creating objects. The <code>creator<\/code> can be an <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-interface\/\">interface<\/a> if it doesn&#8217;t have a shared implementation with the subclasses.<\/li>\n\n\n\n<li><code>Product<\/code>: the abstract class that defines the interface for the objects created by the factory method. Like the <code>Creator<\/code>, the <code>Product<\/code> can be an interface.<\/li>\n\n\n\n<li><code>ConcreteFactory<\/code>: the concrete class that inherits from the <code>Creator<\/code> class. The <code>ConcreteFactory<\/code> class creates <code>ConcreateProduct<\/code> that inherits from the <code>Product<\/code>.<\/li>\n\n\n\n<li><code>ConcreteProduct<\/code>: the concrete class that extends the <code>Product<\/code> class.<\/li>\n<\/ul>\n\n\n\n<p>Here&#8217;s the implementation of the factory method 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\">FactoryMethod<\/span>;\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">abstract<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Product<\/span> {}\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">abstract<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Creator<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">abstract<\/span> Product <span class=\"hljs-title\">FactoryMethod<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>;\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Operation<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> product = FactoryMethod();\n        \n        <span class=\"hljs-comment\">\/\/ process the product<\/span>\n        <span class=\"hljs-comment\">\/\/ ...<\/span>\n        Console.WriteLine(<span class=\"hljs-string\">$\"Work with the <span class=\"hljs-subst\">{product}<\/span>\"<\/span>);\n    }\n}\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ConcreateProduct<\/span>: <span class=\"hljs-title\">Product<\/span> {}\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ConcreteFactory<\/span> : <span class=\"hljs-title\">Creator<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">override<\/span> Product <span class=\"hljs-title\">FactoryMethod<\/span>(<span class=\"hljs-params\"><\/span>)<\/span> =&gt; <span class=\"hljs-keyword\">new<\/span> ConcreateProduct();\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> creator = <span class=\"hljs-keyword\">new<\/span> ConcreteCreator();\n        creator.Operation();\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<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">Work <span class=\"hljs-keyword\">with<\/span> the FactoryMethod.ConcreateProduct<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Factory method pattern vs. the new keyword<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1) The new keyword creates dependencies between the client code and the concrete implementations of classes<\/h3>\n\n\n\n<p>When you use the <code>new<\/code> keyword to create objects of classes, you create dependencies between the client code and the concrete implementation of the classes. <\/p>\n\n\n\n<p>If the classes change, you must change the client code to accommodate the new implementation. This makes your code tightly coupled and difficult to extend.<\/p>\n\n\n\n<p>The Factory Method pattern decouples the client code from the implementation of the objects.<\/p>\n\n\n\n<p>The client code only needs to know the factory interface, which provides a way to create objects without knowing the specific implementation of the objects it creates. <\/p>\n\n\n\n<p>Therefore, the factory method makes your code more flexible, testable, and easier to extend.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2) The new keyword makes it difficult to swap out implementations<\/h3>\n\n\n\n<p>The <code>new<\/code> keyword also makes it difficult to swap out implementations. If you introduce a new implementation or replace an existing one, you must the client code, violating the <a href=\"https:\/\/csharptutorial.net\/csharp-design-patterns\/csharp-open-closed-principle\/\">open-closed principle<\/a>.<\/p>\n\n\n\n<p>On the other hand, using the Factory Method makes it easier to swap out implementations without modifying the client code.<\/p>\n\n\n\n<p>The reason is that the client code only needs to know the factory interface and can use it to create objects without knowing the specific implementation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">C# Factory Method design pattern example<\/h2>\n\n\n\n<p>The following program demonstrates how to use the Factory Method pattern to implement a discount policy for a simplified order system:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" 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\">FactoryMethod<\/span>;\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">abstract<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Discount<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">abstract<\/span> <span class=\"hljs-keyword\">decimal<\/span> <span class=\"hljs-title\">GetPercentage<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>;\n}\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">RegularDiscount<\/span> : <span class=\"hljs-title\">Discount<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">override<\/span> <span class=\"hljs-keyword\">decimal<\/span> <span class=\"hljs-title\">GetPercentage<\/span>(<span class=\"hljs-params\"><\/span>)<\/span> =&gt; <span class=\"hljs-number\">0.1<\/span>m;\n}\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">IrregularDiscount<\/span> : <span class=\"hljs-title\">Discount<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">override<\/span> <span class=\"hljs-keyword\">decimal<\/span> <span class=\"hljs-title\">GetPercentage<\/span>(<span class=\"hljs-params\"><\/span>)<\/span> =&gt; <span class=\"hljs-number\">0.15<\/span>m;\n}\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">abstract<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">DiscountPolicy<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">abstract<\/span> Discount <span class=\"hljs-title\">Create<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>;\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">decimal<\/span> <span class=\"hljs-title\">Apply<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">decimal<\/span> Price<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> discount = Create();\n        <span class=\"hljs-keyword\">return<\/span> Price * (<span class=\"hljs-number\">1<\/span> - discount.GetPercentage());\n    }\n\n}\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">RegularDiscountPolicy<\/span> : <span class=\"hljs-title\">DiscountPolicy<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">override<\/span> Discount <span class=\"hljs-title\">Create<\/span>(<span class=\"hljs-params\"><\/span>)<\/span> =&gt; <span class=\"hljs-keyword\">new<\/span> RegularDiscount();\n}\n\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">IrregularDiscountPolicy<\/span> : <span class=\"hljs-title\">DiscountPolicy<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">override<\/span> Discount <span class=\"hljs-title\">Create<\/span>(<span class=\"hljs-params\"><\/span>)<\/span> =&gt; <span class=\"hljs-keyword\">new<\/span> IrregularDiscount();\n}\n\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Order<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">readonly<\/span> <span class=\"hljs-keyword\">decimal<\/span> _netAmount;\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">decimal<\/span> Amount =&gt; OrderDiscountPolicy.Apply(_netAmount);\n    <span class=\"hljs-keyword\">public<\/span> DiscountPolicy OrderDiscountPolicy\n    {\n        <span class=\"hljs-keyword\">get<\/span>; <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">set<\/span>;\n    }\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-title\">Order<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">decimal<\/span> amount, DiscountPolicy discountPolicy<\/span>)<\/span>\n    {\n        _netAmount = amount;\n        OrderDiscountPolicy = discountPolicy;\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>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> order = <span class=\"hljs-keyword\">new<\/span> Order(<span class=\"hljs-number\">1000<\/span>, <span class=\"hljs-keyword\">new<\/span> IrregularDiscountPolicy());\n        Console.WriteLine(order.Amount);\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><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<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\">850<span class=\"hljs-selector-class\">.00<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>The following UML diagram illustrates how the relationships between classes in the program:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/csharptutorial.net\/wp-content\/uploads\/2023\/05\/csharp-factory-method-design-pattern-example.svg\" alt=\"C# factory method design pattern example\" class=\"wp-image-1800\"\/><\/figure>\n\n\n\n<p>First, define the <code>DiscountPolicy<\/code> as an abstract class. The <code>DiscountPolicy<\/code> class use the <code>Create()<\/code> method that creates and returns a new <code>Discount<\/code> object.<\/p>\n\n\n\n<p>Next, define the <code>RegularDiscountPolicy<\/code> and <code>IrregularDiscountPolicy<\/code> classes that extend the <code>DiscountPolicy<\/code> class. The <code>Create()<\/code> method of these classes returns a <code>RegularDiscount<\/code> and <code>IrregularDiscount<\/code> object, respectively.<\/p>\n\n\n\n<p>Then, define the <code>Discount<\/code> class as an abstract class. The <code>Discount<\/code> class has two concrete classes including <code>RegularDiscount<\/code> and <code>IrregularDiscount<\/code> classes.<\/p>\n\n\n\n<p>After that, define the <code>Order<\/code> class that uses the <code>DiscountPolicy<\/code> class. The <code>Order<\/code> class stores a net amount of the order and a discount policy. The <code>Amount<\/code> property returns the amount after applying the discount policy to the net amount.<\/p>\n\n\n\n<p>Finally, create an <code>Order<\/code> object with a net amount of <code>1000<\/code> and an <code>IrregularDiscountPolicy<\/code> object in the <code>Main()<\/code> method of the <code>Program<\/code> class and displays the amount after applying the discount policy to the console.<\/p>\n\n\n\n<p>In this example, you can swap the discount policy from the <code>IrregularDiscountPolicy<\/code> to <code>RegularDiscountPolicy<\/code> without modifying the <code>Order<\/code> class.<\/p>\n\n\n\n<p>Also, you can introduce a new discount policy e.g., <code>SpecialDiscountPolicy<\/code> and swap it with the current discount policy without changing the <code>Order<\/code> class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the Factory Method design pattern to create objects without tightly coupling the object creation code to the client code.<\/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=\"1528\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-factory-method\/\"\n\t\t\t\tdata-post-title=\"C# Factory Method\"\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=\"1528\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-factory-method\/\"\n\t\t\t\tdata-post-title=\"C# Factory Method\"\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 how to use the C# factory method design pattern to create objects without tightly coupling the object creation code to the client code.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1441,"menu_order":6,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1528","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1528","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=1528"}],"version-history":[{"count":4,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1528\/revisions"}],"predecessor-version":[{"id":2716,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1528\/revisions\/2716"}],"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=1528"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}