簡體   English   中英

工廠模式在 C# 中返回泛型類型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM