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();
}
}