Search code examples
c#design-patternsgenericsfactory-pattern

Could this work as a Generic Factory method?


Just fooling around and I got this idea, is this a good implementation for a generic factory method pattern?

Factory Code:

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

Calling the Factory somewhere else:

 class Program
    {
        static void Main(string[] args)
        {
            var obj = Factory.Create<Person>();
            obj.Name = "Mark";
            Console.WriteLine(obj.Name);

            var obj2 = Factory.Create<Animal>();
            obj2.AnimalType= "Dog";
            Console.WriteLine(obj2.AnimalType);

            dynamic obj3 = Factory.Create<ExpandoObject>();
            obj3.Age= 20;

            Console.WriteLine(obj3.Age);

            Console.ReadKey();
        }
    }

I mean is working as expected... but do you see any problem here? Cause I don't...

Any advice will be more than appreciated because I am planning to use factories to instantiate the objects and these seems good..

Thanks in advance :D

EDIT: I modified the name of the factory method in order to clarify the question since the previous name was GetInstance and It was confusing.


Solution

  • Your code is technically correct but IMO useless. You have no benefit from using this Factory. It's even much easier to use new for every new instance you need. So, this is a problem.

    In fact, it's pretty much defeating the reason to have a factory. It doesn't return an abstraction and it isn't suitable to build an expensive object. Also, your code would be coupled to the Factory.

    A DI Container, autofac is very good, is pretty much a factory and knows how to handle the instantiation of any type registered to it. Also, it can be used to inject any isntance you'd need as a dependency.

    In conclusion, I'd say to use the new keyword for simple cases and a DI Container for objects with dependencies. The Factory class you wrote and its usage seem more like bad code actually, so don't use it in a real app.