Factory Patterns in C# ? Why we use it?

Factory Patterns :- Factory Pattern is a Creational Software Design Pattern and widely used in software developments. It is used for dynamically creating the objcets of the the concrete classes based on some conditions without exposing the logic of instance creation to the User and return the dynamically created object using the Common Interface.

In simple words we can say that factory pattern creates objects at run time and without exposing the creation logic of objects to users. We use an Interface for creating an Object and object creation decision is depends on the subclass based on some conditions.

To implement factory Pattern we have to follow below steps :-

  • Create an Interface in which declare the common method.
  • Create the Product Classes and implemet the Interface into it and provides the implementation of implemented method using specific logics for every product class.
  • Create a Factory Class and inside the factory Class, written a public Static Method that will return an Interface and will create the Instances of the Product Classes based on the specific conditons.
  • In the Client Class or Calling Class create a Reference object of Interface that will store the return the dynamically created object and using this object call the specific methods.

Practical Implementation for Repository Pattern :- For implementing the Factory Pattern in application firstly I have created a Interface ICourse in which i have declare a method ReturnCouserType() and it is returning the String Value.

                
  public interface ICourse
    {
        string ReturnCouserType();
    }                
                

Now I have created four product classes that is PostGraduation Diploma Engineering Medical and define a ReturnCouserType method is returning the string.

                
 public class PostGraduation :ICourse
    {
        public string ReturnCouserType()
        {
            return "You have registered for 2 Years Post graduation Course in Arts";
        }
    }         
                
                
public class Diploma : ICourse
    {
        public string ReturnCouserType()
        {
            return "You have registered for 3 Years Diploma Course";
        }
    }          
                
 public class Engineering :ICourse
    {
        public string ReturnCouserType()
        {
            return "You have registered for 4 Years Engineering Couses";
        }
    }        
             
                
public class Medical :ICourse
    {
        public string ReturnCouserType()
        {
            return "You have registered for 5 Years Medical Courses";
        }
    }        
                

After creating an Interface and product classes now I have created a Factory Class named it CourseFactory and inside it written a public static method named it ChooseCourse and it is creating the dynamic objects of product classes based on a variable Number_of_Years.

Image is not available
                
 public class CourseFactory
    {
        public static ICourse ChooseCourse(int Number_of_Years)
        {
            ICourse course = null;
            if(Number_of_Years==2)
            {
                course = new PostGraduation();
            }
            if (Number_of_Years == 3)
            {
                course = new Diploma();
            }
            if (Number_of_Years == 4)
            {
                course = new Engineering();
            }
            if (Number_of_Years == 5)
            {
                course = new Medical();
            }
            return course;
        }
    }            
                

After creating the factory Class and Interface we have to consume this in client class or Controller or Program class in case of console app as depicted into the below code example.

Image is not available
                
 internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Number of years for course?");
            int number_Of_Years = Convert.ToInt32(Console.ReadLine());
            ICourse courseType = CourseFactory.ChooseCourse(number_Of_Years);
            string course = courseType.ReturnCouserType();
            Console.WriteLine(course);
            Console.ReadKey();
        }
    } 
                

Now run the application and you can see the output as in below images.

Image is not available
Image is not available
Image is not available
Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.