Sunday, October 22, 2023

Factory Method Design Pattern in C#

The Factory Method Design Pattern belongs to the Creational Design Pattern Category.As part of this article, we will discuss this design pattern in detail with example

What is Factory Method Design Pattern

As per Gang of Four, the Factory Method Design Pattern states that Defines an interface for creating an object but lets the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

In simple words, The Factory Method Design Pattern is used when we create the object without exposing the object creation logic to the client. In the factory method design pattern, we will create an abstract class as the Factory class, which will create and return the product instance, but it will let the subclasses decide which class to instantiate.

The Key Components:

  1. Factory Interface/Abstract Class:This serves as a blueprint for an interface or an abstract class that contains a method for creating objects. Typically, this method is named something like 'createProduct()' or 'factoryMethod()'.
  2. Concrete Factories:These are tangible classes that implement the factory interface. They provide specific implementations of the 'createProduct()' method. Each concrete factory is responsible for producing a particular type of product.
  3. Product Interface/Abstract Class:This defines an interface or an abstract class for the products generated by the factories. Product classes usually share common attributes or methods.
  4. Concrete Products:These are the real-deal classes that implement the product interface. Each concrete product embodies a specific type of object.

EXAMPLE TO UNDERSTAND FACTORY Method DESIGN PATTERN IN C#

Let's dive into the Factory Method Design Pattern using a scenario of different beverages in a cafe, which we use in our previous article Factory Design Pattern.

Step-1 : Create the Abstract Product or Product Interface (Beverage)

We need to create either an interface or an abstract class that will expose the operations a beverage should have. So, create a interface file named IBeverage.cs and copy and paste the following code.

 public interface IBeverage
    {
        public string Serve();
    }

Now We will create two Product classes to implement the above interface.

Step-2 : Creating Product Classes(Coffee and Tea)

In our example we will take two beverage products- Coffee and Tea. So we will create two classes by implementing the IBeverage.cs interface. Thse two classes will be:- Coffee.cs and Tea.cs

Coffee.cs
 public class Coffee : IBeverage
    {
        public string Serve()
        {
            return "Serving Coffee";
        }
    }
Tea.cs
 public class Tea:IBeverage
    {
        public string Serve()
        {
            return "Serving Tea";
        }
    }

So, we have created two Product classes Coffee.cs and Tea.cs that implements the IBeverage.cs interface. Now we will create the Factory class.

Step-3 : Creating Factory Interface(IBeverageFactory)

Create a interface file named IBeverageFactory.cs.This interface will contain a method for creating object named createBeverage()

 using FactoryMethodDesignPatternDemo.Product;

namespace FactoryMethodDesignPatternDemo.Factory
{
    public  interface IBeverageFactory
    {
        public IBeverage createBeverage();
    }
}

Step-4 : Create concrete factorie classes(CoffeeFactory and TeaFactory)

The concrete factory class implements the Factory interface class and overrides the factory method. The override Factory Method will return an instance of a Concrete Product via the base Product interface.As we have two types of beverage, we will create two concrete factory classes- CoffeeFactory.cs and TeaFactory.cs

CoffeeFactory.cs
using FactoryMethodDesignPatternDemo.Product;

namespace FactoryMethodDesignPatternDemo.Factory
{
    public class CoffeeFactory : IBeverageFactory
    {
        public IBeverage createBeverage()
        {
            return new Coffee();
        }
    }
}

TeaFactory.cs
using FactoryMethodDesignPatternDemo.Product;

namespace FactoryMethodDesignPatternDemo.Factory
{
    public class TeaFactory : IBeverageFactory
    {
        public IBeverage createBeverage()
        {
            return new Tea();
        }
    }
}

Step-5 : Consuming the Factory Method in the Client Code

The client code works with an instance of a concrete factory, i.e., we need to create an instance of either CoffeeFactory,or TeaFactory. Then, we need to call the createBeverage method on the concrete factory instance, which will return the actual product instance via the product interface, i.e., Beverage type.

using FactoryMethodDesignPatternDemo.Factory;
using FactoryMethodDesignPatternDemo.Product;
//CoffeeFactory createBeverage method will return an instance of Coffee Product
IBeverage coffee =new CoffeeFactory().createBeverage();
if (coffee != null)
{
    Console.WriteLine(coffee.Serve());
}
Console.WriteLine("--------------------------------");
//TeaFactory createBeverage method will return an instance of Tea Product
IBeverage tea = new TeaFactory().createBeverage();
if (tea != null)
{
    Console.WriteLine(tea.Serve());
}
Console.ReadLine();

When we run the application, it displays the output as expected, as shown in the below image.

factory method design pattern

UML(Class) Diagram

factory method design pattern uml

The Factory Method Design Pattern is particularly useful in scenarios where you want to decouple the client code from the specific classes it needs to instantiate, making your code more maintainable and easier to extend.

The full source code is available here:

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top