Factory Design Pattern in C# with Real-Time Example

 

Factory Design Pattern in C# with Real-Time Example

 

In this article, I will talk about the Factory Design Pattern in C# with models. The Factory Design Pattern is one of the most often utilized plan designs progressively applications. The Factory Design Pattern in C# falls under the classification of Creational Design Pattern.

What is Factory Design Pattern in C#?

As per Gang of Four, the Factory Design Pattern states that “Define an interface for creating an object, but let sub-classes decide which class to instantiate. The Factory method lets a class defer instantiation it uses to sub-classes”

Factory pattern is one of the most used design patterns in real world applications

Factory pattern creates object without exposing the creation logic to the client and refer to newly created object using a common interface

From the above diagram, client uses factory and creates the product.

The basic principle behind the factory design pattern is that, at run time, we get an object of a similar type based on the parameter we pass. 


Understanding the Factory Design Pattern in C# with one real-time example
To understand the Factory design pattern, we are going to implement an application saying Car management system.

In this project we will create couple of the classes and a interface , called CarInterface, this interface will have below methods

        string GetCarModel();
        string GetColor();
        int GetCarPrice(); 

we will create classes which will be inherited from the Car interface.



Without using the Factory Design Pattern in C#

As pre this logic , when we will give the car model from application, it should return the result, like below.


1. Lets create a project in visual studio and create a interface class with below methods

    public interface Cars

    {

        string GetCarModel();

        string GetColor();

        int GetCarPrice();

    }

 2. Now lets create CarModel classes

    1. HondaModelCars.cs

 

    public class HondaModelCars : Cars

    {

        public string GetCarModel()

        {

            return "Honda Model";

        }

        public string GetColor()

        {

            return "Red";

        }

        public int GetCarPrice()

        {

            return 100000;

        }

    }


2. BMWModelCars.cs

 

public class BMWModelCars : Cars

    {

        public string GetCarModel()

        {

            return "BMW Model";

        }

        public string GetColor()

        {

            return "Black";

        }

        public int GetCarPrice()

        {

            return 200000;

        }

    }


3. FerrariModelCars.cs

 

public class FerrariModelCars : Cars

    {

        public string GetCarModel()

        {

            return "Ferrari Model";

        }

        public string GetColor()

        {

            return "Blue";

        }

        public int GetCarPrice()

        {

            return 500000;

        }

    }


Now lets run this application from main method like below

 

static void Main(string[] args)

        {

            Console.WriteLine("Enter the Car Model : ");

 

            string carModel = Console.ReadLine();

            Cars carsDetails = null;

        

            if (carModel.ToLower() == "honda")

            {

                carsDetails = new HondaModelCars();

            }

            else if (carModel.ToLower() == "bmw")

            {

                carsDetails = new BMWModelCars();

            }

            else if (carModel.ToLower() == "ferrari")

            {

                carsDetails = new FerrariModelCars();

            }

            if (carsDetails != null)

            {

                Console.WriteLine("Car Model : " + carsDetails.GetCarModel());

                Console.WriteLine("Car color : " + carsDetails.GetColor());

                Console.WriteLine("Car price :" + carsDetails.GetCarPrice());

            }

            else

            {

                Console.Write("Car Model is not available");

            }

            Console.ReadLine();

        }


After run this application , below is the output


What is the Problem of the above code implementation?

The above code implementation introduces the following problems

  1. First, here we can see it is the tight coupling between the client class (Program) and Product Class (HondaCars, BMWcars, and FerrariCars).
  2. Secondly, if we add a new Car type, then also we need to modify the Main method by adding an extra if-else condition which not only increase the development code but also in the testing 

Let us see how to overcome the above problem by using the factory design pattern.

Factory Design Pattern Implementation in C#:
As per the factory design pattern creates object without exposing the creation logic to the client and refer to newly created object using a common interface

So for achieving factory design pattern ,lets make some changes ,so for that create a CarFactory class like below

 

    public class CarFactory

    {

        public static Cars GetCarModelInfo(string CarModelName)

        {

            Cars carsDetails = null;

            if (CarModelName.ToLower() == "honda")

            {

                carsDetails = new HondaModelCars();

            }

            else if (CarModelName.ToLower() == "bmw")

            {

                carsDetails = new BMWModelCars();

            }

            else if (CarModelName.ToLower() == "ferrari")

            {

                carsDetails = new FerrariModelCars();

            }

            return carsDetails;

        }

    }           

                Console.WriteLine("Car Model : " + carsDetails.GetCarModel());

                Console.WriteLine("Car color : " + carsDetails.GetColor());

                Console.WriteLine("Car price :" + carsDetails.GetCarPrice());

            }

            else

            {

                Console.Write("Car Model is not available");

            }

            Console.ReadLine();

        }

 
Modifying the Client Class

 

        static void Main(string[] args)

        {

            Console.WriteLine("Enter the Car Model : ");

 

            string carModel = Console.ReadLine();

            Cars carsDetails = CarFactory.GetCarModelInfo(carModel);

 

            if (carsDetails != null)

            {

                Console.WriteLine("Car model : " + carsDetails.GetCarModel());

                Console.WriteLine("Car color : " + carsDetails.GetColor());

                Console.WriteLine("Car Price :" + carsDetails.GetCarPrice());

            }

            else

            {

                Console.Write("Invalid Car Model");

            }

            Console.ReadLine();

        }



Conclusion:

So, today we have learned what Factory Design Pattern is and why and where can be used with Real World Example.

Share this

Related Posts

Previous
Next Post »