Factory Design Pattern

Defines an interface for creating an object of a class and hides the complexity of creating that object.

For example

When we visit a pizza store and order a pizza, after some background/hidden process we get pizza. What we do is just ask for a pizza and choice of toppings; we do not need to know about the complexity of creating pizza.

In the same way, by using Factory Pattern, we can hide the complexity of creating an object.

A very simple example of creating Factory Pattern in C# is as follows:

  1. public class FactoryArgs  
  2.     {  
  3.         public string ShapeType { getset; }  
  4.         public string ShapeColor { getset; }  
  5.     }  
  6.     public class ShapeFactory  
  7.     {  
  8.         public static IShape GetShape(FactoryArgs args)  
  9.         {  
  10.             if (args.ShapeType == "Rectangle")  
  11.                 return new Rectangle() { FillColor = args.ShapeColor };  
  12.             else  
  13.                 return new Circle() { FillColor = args.ShapeColor };  
  14.         }  
  15.     }  
  16.   
  17.     public class Rectangle : IShape  
  18.     {  
  19.         public string FillColor  
  20.         {  
  21.             getset;  
  22.         }  
  23.   
  24.         public void DrawShape()  
  25.         {  
  26.             Console.WriteLine(string.Format("Creating rectangle shape and filling {0} color", FillColor));  
  27.         }  
  28.     }  
  29.     public class Circle : IShape  
  30.     {  
  31.         public string FillColor  
  32.         {  
  33.             getset;  
  34.         }  
  35.   
  36.         public void DrawShape()  
  37.         {  
  38.             Console.WriteLine(string.Format("Creating circle shape and filling {0} color", FillColor));  
  39.         }  
  40.     }  
  41.   
  42.     public interface IShape  
  43.     {  
  44.         void DrawShape();  
  45.     }  
In this example, we have ShapeFactory class responsible for creating object of IShape based on arguments we passed.

So, the client doesn't need to worry how the IShape object will be created, they just need to ask for what shape and color they want. Based on the client’s choice, factory will decide which object it will create.
  1. IShape _shape = ShapeFactory.GetShape(new FactoryArgs {ShapeType="Circle",ShapeColor = "red" });  
  2. _shape.DrawShape();  
  3. Console.ReadLine();  
Output: Creating circle shape and filling red color.
  1. _shape = ShapeFactory.GetShape(new FactoryArgs { ShapeType = "Rectangle", ShapeColor = "black" });  
  2. _shape.DrawShape();  
  3. Console.ReadLine();  
Output: Creating rectangle shape and filling black color.