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?