I am wondering what is the most efficient way to make a parameterized
factory method, and before I start spending time on performance
measurements myself, I would like to hear the NG's opinion:
I want my parameterized factory method to create either an object of
type A or an object of type B, depending on the type of the Input
parameter in the factory method. The type can be tested using the 'is'
operator, but alternatively, the input could have an enumerated type
field, which can be tested in a switch statement.
The 'is' operator approach is easist to do, but my guess is that using
the enum approach cannot be less performant than the 'is' operator
approach (but it uses more memory). Are there any significant
performance differences between the two examples below ? (Assume that
it not is an option to implement the creational code in the derived
input classes which would be the best OO way to it):
// 1)
// 'is' operator approach
class A : IFactoryProduct {...}
class B : IFactoryProduct {...}
class Input {...}
class Ainput : Input {...}
class Binput : Input {...}
class SomeClass
{
public IFactoryProduct FactoryMethod(Input input)
{
if(input is Ainput) return new A();
if(input is Binput) return new B();
}
}
// 2)
// Approach using an enumeration.
// The Input class now has a InputType field.
class A : IFactoryProduct {...}
class B : IFactoryProduct {...}
enum InputType { A, B};
class Input { ... public InputType typeField; ... }
class Ainput : Input {...}
class Binput : Input {...}
class SomeClass
{
public IFactoryProduct FactoryMethod(Input input)
{
IFactoryProduct result;
switch(Input.typeField)
{
case: InputType.A:
{
result = new A();
break;
}
case: InputType.B:
{
result = new B();
break;
}
return result;
}
}
}
regards
Stig Nielsson