我有一个抽象基类,TestFactory如下所示:
public abstract class TestFactory
{
//static method that can create concrete factories
public static TestFactory CreateTestFactory(FactoryType factoryType)
{
TestFactory factory = null;
switch (factoryType)
{
case FactoryType.Blood:
factory = new BloodTestFactory();
break;
case FactoryType.Urine:
factory = new UrineTestFactory();
break;
default:
break;
}
return factory;
}
//BloodTestFactory and UrineTestFactory are concrete types
//that will need to create their own tests
//this enum parameter needs to 'switch' between
//BloodTestType and UrineTestType
public abstract LabTest CreateTest(Enum e);
}
public enum FactoryType
{
Blood,Urine
}
Run Code Online (Sandbox Code Playgroud)
所以这个类创建了一个具体的工厂,例如:
public class BloodTestFactory :TestFactory
{
//both BloodTestFactory and UrineTestFactory will create a LabTest object
//I would like to have a BloodTestType and UrineTestType enum, what do I need
//to do to pass a generic Enum as a parameter and then switch on BloodTestType
public override LabTest CreateTest(Enum e)
{
BloodTest bt = null;
//switch (e)
//{
// default:
// break;
//}
//creation logic here
}
}
public enum BloodTestType
{
H1AC,Glucose
}
Run Code Online (Sandbox Code Playgroud)
ABloodTest本身是一个抽象类,它将BloodTest根据 Enum 值返回一个具体对象。为了清楚起见,我想要一个BloodTestType和一个UrineTestType(未显示)枚举。由于该CreateTest方法是抽象的,如何确保BloodTestType当我想创建BloodTests时可以传递 a UrineTestType,当我想创建 UrineTest 时可以传递 enum ?
我不确定这是否是满足此要求的最佳方法,我将留下设计模式讨论以供评论/其他答案。
我不一定会这样做,但是,为了使您的代码能够工作,我会TestFactory为enum.
public abstract class TestFactory<TTestType>
{
public abstract LabTest CreateTest(TTestType testType);
}
Run Code Online (Sandbox Code Playgroud)
然后,派生类只需指定通用参数:
public class BloodTestFactory : TestFactory<BloodTestType>
{
public override LabTest CreateTest(BloodTestType e)
{
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,除非您使用Unconstrained Melody之类的东西,否则您不会在enum.
另请注意,现在这使得引用共享基类变得困难,因为您需要关闭通用参数:
TestFactory baseReference = myBloodTestFactory; // Not possible.
TestFactory<BloodTestType> baseReference = myBloodTestFactory;
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我可能会将这两个工厂分解为没有基础的独立类,或者考虑使用接口。在您想要的“通用”方法中处理特定参数是很困难的。