C# – Is it a good idea to have a factory class using generics to instantiate objects

c++factorygenerics

Is it a good idea to have a factory class using generics to instantiate objects?

Let's say I have a class Animal and some subclasses (Cat, Dog, etc):

abstract class Animal
{
    public abstract void MakeSound();
}

class Cat : Animal
{
    public override void MakeSound()
    {
        Console.Write("Mew mew");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.Write("Woof woof");
    }
}

static class AnimalFactory
{
    public static T Create<T>() where T : Animal, new()
    {
        return new T();
    }
}

Then in my code I would use AnimalFactory like this:

class Program
{
    static void Main(string[] args)
    {
        Dog d = AnimalFactory.Create<Dog>();
        d.MakeSound();
    }
}

Best Solution

Depends on what you want to do with it. The example you gave is not that helpful, as all it does is simply call new() which is something you can do in your code as well. A factory is more useful if you want to place logic which has to be ran during the object creation process somewhere outside the object to create but also away from the code which instantiates the objects.

In that light, it depends on what logic you want to run in your factory and if that logic is also writable using the same generic constraints as the factory. If not, you'll likely need a pattern called Abstract factory, which uses a general factory to instantiate the right specific factory behind the scenes for the type to create the object at hand.

Related Question