Search code examples
c#design-patternsfactory-pattern

Factory pattern implementation


I need to create one of a number of different objects based on some value and I was advised to look into the Factory patterns. I do not want my client having to decide which object to create or to require hard-coded class names, so after doing some reading I came up with the following (simplified) example:

public class ObjectA : IObject 
{
}

public class ObjectA : IObject 
{
}

public interface IObjectFactory
{
    IObject CreateObject(ObjectCreationParameters p);
}

public abstract ObjectFactory : IObjectFactory
{
    abstract IObject CreateObject(ObjectCreationParameters p);
}

public ConcreteObjectFactory : ObjectFactory
{
    public IObject CreateObject(ObjectCreationParameters p)
    {
        IObject obj;
        switch (p.Value)
        {
            case A:
              obj = new ObjectA();
              break;
            case A:
              obj = new ObjectB()
              break;
        }
        return obj;
    }
}

The above works but I am a little confused as to whether my implementation is correct or not.

I would prefer not to have an ObjectAFactory and an ObjectBFactory as in a Factory Method pattern if it can be avoided, however, my object hierarchy does not seem to follow the same object hierarchy as in example of the Abstract Factory pattern. I do not have an ObjectA2 or ObjectB2 that would ever be created via a ConcreteObject2Factory.

Is my implementation correct or am I doing something wrong and if so, what?


Solution

  • Yes, it is a correct implementation. This switch statement may seem to be problematic and non-polymorphic but in fact, you can read about it in an excellent Code Clean book, rule G23: Prefer Polymorphism to If/Else or Switch/Case:

    “ONE SWITCH” rule: There may be no more than one switch statement for a given type of selection. The cases in that switch statement must create polymorphic objects that take the place of other such switch statements in the rest of the system.

    Your implementation abstracts creation of concrete object, co client don't have to worry about it and that is what this design pattern is for. Look also, for example, at Encapsulation section in the Wikipedia entry.