The Factory Design Pattern is a creational design pattern in C# and .NET that provides an interface for creating objects but allows subclasses to alter the type of objects that will be created. It is part of the larger family of design patterns known as the “Factory” patterns.

The Factory pattern is used to create objects without specifying the exact class of object that will be created.

Here’s how the Factory Design Pattern works in C#:

  1. Define a common interface or abstract class: Create an interface or an abstract class that declares the factory method(s). This interface or abstract class defines the contract that concrete factories must implement.
public interface IProduct
{
    void DoSomething();
}
  1. Create concrete implementations: Implement one or more concrete classes that implement the interface or extend the abstract class. These classes represent the different types of objects that can be created.
public class ConcreteProductA : IProduct
{
    public void DoSomething()
    {
        Console.WriteLine("Product A is doing something.");
    }
}

public class ConcreteProductB : IProduct
{
    public void DoSomething()
    {
        Console.WriteLine("Product B is doing something.");
    }
}
  1. Create a factory class: Define a factory class that contains the factory method(s). This factory class is responsible for creating objects based on certain conditions or parameters.
public class ProductFactory
{
    public IProduct CreateProduct(string productType)
    {
        if (productType == "A")
        {
            return new ConcreteProductA();
        }
        else if (productType == "B")
        {
            return new ConcreteProductB();
        }
        else
        {
            throw new ArgumentException("Invalid product type");
        }
    }
}
  1. Use the factory to create objects: In your client code, use the factory to create objects instead of directly instantiating concrete classes. Pass the appropriate parameters to the factory to specify the type of object you want to create.
class Program
{
    static void Main()
    {
        ProductFactory factory = new ProductFactory();

        IProduct productA = factory.CreateProduct("A");
        productA.DoSomething();

        IProduct productB = factory.CreateProduct("B");
        productB.DoSomething();
    }
}

In this example, the ProductFactory class is responsible for creating objects of type IProduct. Depending on the input parameter (e.g., “A” or “B”), it decides which concrete class to instantiate. This allows you to create objects without knowing the exact class and helps decouple the client code from the concrete classes.

The Factory Design Pattern provides flexibility in object creation and makes it easy to add new types of objects without modifying existing code. It promotes the “open-closed” principle of software design, which means that the code should be open for extension but closed for modification.

By davs