Monday, February 17, 2025

C# Creational Factory

📁 File Structure

/FactoryMethodPattern
│── IProduct.cs
│── ConcreteProductA.cs
│── ConcreteProductB.cs
│── Creator.cs
│── ConcreteCreatorA.cs
│── ConcreteCreatorB.cs
│── Program.cs
    

1. IProduct.cs (Abstract Product Interface)

namespace FactoryMethodPattern
{
    // Abstract Product Interface
    public interface IProduct
    {
        void Use();
    }
}
    

2. ConcreteProductA.cs & ConcreteProductB.cs (Concrete Products)

ConcreteProductA.cs

using System;

namespace FactoryMethodPattern
{
    // Concrete Product A
    public class ConcreteProductA : IProduct
    {
        public void Use()
        {
            Console.WriteLine("Using ConcreteProductA");
        }
    }
}
    

ConcreteProductB.cs

using System;

namespace FactoryMethodPattern
{
    // Concrete Product B
    public class ConcreteProductB : IProduct
    {
        public void Use()
        {
            Console.WriteLine("Using ConcreteProductB");
        }
    }
}
    

3. Creator.cs (Abstract Factory Class)

namespace FactoryMethodPattern
{
    // Abstract Creator
    public abstract class Creator
    {
        // Factory Method: Must be implemented by concrete creators
        public abstract IProduct FactoryMethod();
    }
}
    

4. ConcreteCreatorA.cs & ConcreteCreatorB.cs (Factory Implementations)

ConcreteCreatorA.cs

namespace FactoryMethodPattern
{
    // Concrete Creator A
    public class ConcreteCreatorA : Creator
    {
        public override IProduct FactoryMethod()
        {
            return new ConcreteProductA();
        }
    }
}
    

ConcreteCreatorB.cs

namespace FactoryMethodPattern
{
    // Concrete Creator B
    public class ConcreteCreatorB : Creator
    {
        public override IProduct FactoryMethod()
        {
            return new ConcreteProductB();
        }
    }
}
    

5. Program.cs (Client Code)

using System;

namespace FactoryMethodPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a factory for ProductA
            Creator creatorA = new ConcreteCreatorA();
            IProduct productA = creatorA.FactoryMethod();
            productA.Use(); // Output: Using ConcreteProductA

            // Create a factory for ProductB
            Creator creatorB = new ConcreteCreatorB();
            IProduct productB = creatorB.FactoryMethod();
            productB.Use(); // Output: Using ConcreteProductB
        }
    }
}
    

🎯 Key Takeaways

  • Encapsulation: The client does not know which concrete product it gets.
  • Scalability: Easily add new products and factories.
  • Decoupling: The factory method isolates the creation logic.

No comments:

Abstract Factory Pattern in C#

Below is a C# implementation of the Abstract Factory design pattern, a Creational pattern, following the Gang of Four (GoF) structure....