Good people of stackoverflow,
As always, I am writing a factory in order to dynamically instantiate objects.
To schematize, I have four types:
class CatDescriptor : PetDescriptor
class DogDescriptor : PetDescriptor
class Cat : Pet
class Dog : Pet
I instanciate the two last types from the factory. And here comes the dilemma: Should I just test the descriptor types with the "is" operator which hides reflection and then cost something.
static Pet.Factory(PetDescriptor descriptor)
{
if (descriptor is CatDescriptor)
{
return new Cat();
}
else if (...)
{
...
}
}
Should I use an Enum "Type" as an attribute embedded in the PetDescriptor.
class PetDescriptor
{
public Type PetType;
public enum Type
{
Cat,
Dog
}
}
static Pet.Factory(PetDescriptor descriptor)
{
switch (descriptor.PetType)
{
case PetDescriptor.Type.Cat:
return new Cat();
....
}
}
Or use virtual methods:
class PetDescriptor
{
public virtual bool IsCat()
{
return false;
}
...
}
class CatDescriptor : PetDescriptor
{
public override bool IsCat()
{
return true;
}
}
static Pet.Factory(PetDescriptor descriptor)
{
if (descriptor.IsCat())
{
return new Cat();
}
else if (...)
{
...
}
}
Votes are opened !
edit: question is about reflection performance, and not factory design.