[英]Factory pattern return generic types in c#
public interface IRequestProcessor<out T>
{
T Translate(string caseId);
}
public class xyzReqProcessor : IRequestProcessor<xyzType>
{
public xyzType Process(string xyzMsg)
{
return new xyz();
}
}
public class VHDReqProcessor : IRequestProcessor<VHDType>
{
public VHDType Process(string xyzMsg)
{
return new VHD();
}
}
直到这里看起来不错。 现在我想用工厂初始化类,但它无法返回 IRequestProcessor 类型的对象。
public static IRequestProcessor Get(FormType translatorType)
{
IRequestProcessor retValue = null;
switch (translatorType)
{
case EFormType.VHD:
retValue = new VHDProcessor();
break;
case EFormType.XYZ:
retValue = new XYZProcessor();
break;
}
if (retValue == null)
throw new Exception("No Request processor found");
return retValue;
}
在调用 Factory.Get(FormType translateType) 方法时,我不想指定任何固定的对象类型,如下所示
Factory.Get<XYZType>(FormType 转换器类型)
我不确定这个解决方案是否适合您的整体设计,但通过这个技巧,您可以实现您的要求。 关键是要有两个接口,一个是通用接口,一个不是非通用接口将调用路由到通用接口的地方。 见下图:
public abstract class BaseType
{
public abstract void Execute();
}
public class VhdType : BaseType
{
public override void Execute()
{
Console.WriteLine("Vhd");
}
}
public class XyzType : BaseType
{
public override void Execute()
{
Console.WriteLine("Xyz");
}
}
public interface IRequestProcessor
{
BaseType Process();
}
public interface IRequestProcessor<T> : IRequestProcessor where T : BaseType, new()
{
T Process<TInput>() where TInput : T;
}
public class VhdRequestProcessor : IRequestProcessor<VhdType>
{
public BaseType Process()
{
return Process<VhdType>();
}
public VhdType Process<TInput>() where TInput : VhdType
{
return new VhdType();
}
}
public class XyzRequestProcessor : IRequestProcessor<XyzType>
{
public BaseType Process()
{
return Process<XyzType>();
}
public XyzType Process<TInput>() where TInput : XyzType
{
return new XyzType();
}
}
public class RequestFactory
{
public IRequestProcessor GetRequest(string requestType)
{
switch (requestType)
{
case "vhd": return new VhdRequestProcessor();
case "xyz": return new XyzRequestProcessor();
}
throw new Exception("Invalid request");
}
}
用法示例:
IRequestProcessor req = new RequestFactory().GetRequest("xyz");
BaseType r = req.Process();
r.Execute();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.