0

I have this factory:

public static class ClassFactory
{
    public static IEnumHereClass CreateClass(EnumHere type)
    {
        switch (type)
        {
            case EnumHere.First:
                return new EnumHereFirstClass();
            case EnumHere.Second:
                return new EnumHereSecondClass();
            default:
                throw new NotSupportedException();
        }
    }
}

Looks nice. But I see problem here: I can't inject it using IoC container (unity for instance) and can't mock it. I want to make this changes (use interface to inject it and delete static):

public class ClassFactory : IClassFactory
{
    public IEnumHereClass CreateClass(EnumHere type)
    {
        switch (type)
        {
            case EnumHere.First:
                return new EnumHereFirstClass();
            case EnumHere.Second:
                return new EnumHereSecondClass();
            default:
                throw new NotSupportedException();
        }
    }
}

What do you think?

mtkachenko
  • 5,389
  • 9
  • 38
  • 68
  • What is your specific question? – Matten Jan 11 '16 at 13:38
  • Use static factory or not? What disadvantages or misunderstanding or do you see in my code? – mtkachenko Jan 11 '16 at 13:41
  • For the record, [using a switch case statement inside of an abstract factory is a code smell](http://stackoverflow.com/questions/31950362/factory-method-with-di-and-ioc/31971691#31971691) indicating there is a problem with the design. Also, using an `Enum` to specify the type is a bad practice because it means you need to change more than one class when the enum type changes. – NightOwl888 Jan 11 '16 at 17:35
  • Also see this alternative approach: http://stackoverflow.com/questions/31950362/factory-method-with-di-and-ioc/#31956803 – NightOwl888 Jan 11 '16 at 17:36

1 Answers1

0

Take a look at the Abstract Factory Pattern

Intent

Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes.


I see this question has been tagged previously with and now . Not to be confused with abstract factory.

Community
  • 1
  • 1
radarbob
  • 4,964
  • 2
  • 23
  • 36
  • I know about abstract fatory but I don't have "family of related objects". I just want to create object instance according to passed enum value. – mtkachenko Jan 11 '16 at 13:49
  • You mentioned IOC container, which made me think you have 2 or more different sets of classes you want to build. Instantiate the appropriate factory for a given set - I imagine an `enum` for that too - then call that factory as shown in the OP. – radarbob Jan 11 '16 at 13:56