Factory Method Design Pattern in C#


Factory Method Design Pattern in C# with Real-time Example 

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

Note: The main point that you want to recall is the Factory Method design isn't precisely the same as the basic Factory Design Pattern that we examined in our past article. A great many people feel that both are something similar and accordingly they utilize the terms Factory and Factory technique reciprocally which isn't right.

What is Factory Method Design Pattern?

According to Gang of Four DefinitionDefine an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses”.

Let us simplify the above definition. The Factory Method Design Pattern is used, when we need to create the object (i.e. instance of the Product class) without exposing the object creation logic to the client. To achieve this, in the factory method design pattern we will create an abstract class as the Factory class which will create and return the instance of the product, but it will let the subclasses decide which class to instantiate. If this is not clear at the moment then don’t worry, I will explain this with one real-time example.

Understanding the Factory Method Design Pattern with Real-time Example:

To understand the Factory method 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.


As per the definition of the Factory Method Design Pattern, we need to create an abstract class or interface for creating the object.
like below we will are going to create a class like below







As you can see, the above abstract class (i.e. CarFactory) contains two methods, one abstract method i.e. CarInfo() and one concrete method i.e. CarDetails(). The CarDetails() method internally calls the CarInfo() method of the subclass which will create the product instance and return that instance.

 Please have a look at the following diagram. As we have three car model (i.e. Honda, BMW, and Ferrari), so here we created three subclasses (i.e. HondaFactory, BMWFactory, and FerrariFactory) of the Abstract CarFactory class and implement the CreateCarProduct() method. This method is going to return the actual product object i.e. (Honda, BMW, and Ferrari).



Below is the Client code , from where we will call concrete class


Implementing the Factory Method Design Pattern in C#
Create a Factory class

  

   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;

        }

    }



Creating Abstract class

The Abstract Creator declares the factory method, which returns an object of type Product. As per the definition, we need to create an abstract class or interface for creating the object. So, let us create an abstract class that will be our factory class with a publicly exposed method. That method is nothing but the factory method which will return the instance of the product. So create a class file with the name CarFactory.cs and then copy and paste the following code in it.

    public abstract class CarFactory

    {

        protected abstract Cars CreateCarProduct();

        public Cars CarDetails()

        {

            return this.CreateCarProduct();

        }

    }


We created the above abstract class with one abstract method i.e. CreateCarProduct() and one concrete method i.e. CarDetails(). The CarDetails() method internally calls the CreateCarProduct() method of the subclass which will create the product instance and return that instance.

Concrete  classes

Now create a Concrete product class and inherit all factory class from abstract class
The Concrete Creator object overrides the factory method to return an instance of a Concrete Product. As we have three types of Cars, so we are going to create three classes (HondaFactory, BMWFactory, and FerraryFactory) which will implement the abstract CarFactory class. So, create a class file with the name ConcreteProduct.cs and then copy and paste the following code into it.
Concreteproduct.cs

 

public class HondaFactory : CarFactory

    {

        protected override Cars CreateCarProduct()

        {

            Cars _model = new HondaModelCars();

            return _model;

        }

    }

    public class BMWFactory : CarFactory

    {

        protected override Cars CreateCarProduct()

        {

            Cars _model = new BMWModelCars();

            return _model;

        }

    }

    public class FerrariFactory : CarFactory

    {

        protected override Cars CreateCarProduct()

        {

            Cars _model = new FerrariModelCars();

            return _model;

        }

    }



As you can see the above three classes implement the CreateCarProduct method of the CarFactory class. That’s it. We are done with our implementation. Let’s compare the Gang of Four Definition with our example.

According to Gang of Four, we need to define an interface or abstract class for creating an object. In our example, it is an abstract class i.e. CarFactory class. The second part of the definition saying that let the subclasses decide which class to instantiate. In our example, the subclasses are HondaFactoryBMWFactory, and FerraryFactory. So these subclasses will decide which class to instantiate, for example, Honda, BMW, and Ferrary.



Now lets call these factory class from main method.

 

  static void Main(string[] args)

        {          

            Cars _car = new HondaFactory().CarDetails();

            if (_car != null)

            {

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

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

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

            }

            else

            {

                Console.Write("Invalid Car Type");

            }

            Console.WriteLine("--------------");

            _car = new BMWFactory().CarDetails();

            if (_car != null)

            {

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

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

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

            }

            else

            {

                Console.Write("Invalid Car Type");

            }

            Console.ReadLine();

        }


After running this , below is the output.


Conclusion:

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

Share this

Related Posts

Previous
Next Post »

1 comments:

Write comments
Anonymous
February 6, 2022 at 12:59 AM delete


Nice and simple way to understand the Factory method design pattern . Thanks

Reply
avatar