How to use Factory Method Pattern in C#

This post shows you how to use Factory Method pattern in C# code.

Factory Method pattern is used to define an interface that creates an object, but only for the subclass to decide which class is used to create the object according to that class.

It can be used to create the first interface class and specify the following concrete class.

Regular usage: Very high

UML Diagram

Factory Method Pattern in C#

 

lasses and objects that participate in this pattern include:

- Product: defines the interface of the object that the factory method creates.

- ConcreteProduct: implements Product interface classes.

- Creator: Defining a factory method, returning one object is a specific type of product. Creator can be the default factory method that returns the default ConcreteProduct object, it can call the factory method to create the Product object.Defining a factory method

- ConcreteCreator override factory method to return the ConcreteProduct instance.

Implement C# code

class BuilderPattern
{
    static void Main()
    {
        Creator[] creators = new Creator[2];
        creators[0] = new ConcreteCreatorA();
        creators[1] = new ConcreteCreatorB();
        foreach (Creator creator in creators)
        {
            Product product = creator.FactoryMethod();
            Console.WriteLine("Created {0}",
              product.GetType().Name);
        }
    }
}

abstract class Product
{
}

class ConcreteProductA : Product
{
}

class ConcreteProductB : Product
{
}

abstract class Creator
{
    public abstract Product FactoryMethod();
}

class ConcreteCreatorA : Creator
{
    public override Product FactoryMethod()
    {
        return new ConcreteProductA();
    }
}

class ConcreteCreatorB : Creator
{
    public override Product FactoryMethod()
    {
        return new ConcreteProductB();
    }
}

Result

Created ConcreteProductA
Created ConcreteProductB