工厂模式返回c#中的泛型类型

时间:2018-02-09 14:11:05

标签: c# .net generics interface factory-pattern

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 translatorType)方法时我不想指定任何固定的对象类型,如下所示

  

Factory.Get&LT; XYZType&gt;(FormType translatorType)

1 个答案:

答案 0 :(得分:1)

我不确定这个解决方案是否适合您的整体设计,但通过这个技巧,您可以实现您所要求的。关键是要有两个接口,一个是通用的,一个不是非通用接口路由调用泛型的接口。见下文:

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();