stackoverflow的好人,
与往常一样,我正在编写一个工厂以动态实例化对象。
为了模式化,我有四种类型:
class CatDescriptor : PetDescriptor
class DogDescriptor : PetDescriptor
class Cat : Pet
class Dog : Pet
我从工厂实例化了最后两种类型。困境来了:我是否应该只用隐藏反射的“is”运算符测试描述符类型,然后花费一些东西。
static Pet.Factory(PetDescriptor descriptor)
{
if (descriptor is CatDescriptor)
{
return new Cat();
}
else if (...)
{
...
}
}
我应该使用枚举“类型”作为嵌入在 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();
....
}
}
或者使用虚拟方法:
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 (...)
{
...
}
}
投票已开启!
编辑:问题是关于反射性能,而不是工厂设计。