IRequest / IResponse模式

时间:2010-05-28 00:35:47

标签: c# .net oop

我正在尝试为Web API请求创建一个基于接口的请求/响应模式,以允许异步的消费者/生产者处理,但不确定我将如何知道底层的IResponse类是什么。

public void Run()
{
   List<IRequest> requests = new List<IRequest>();
   List<IResponse> responses = new List<IResponse();
   requests.Add(AmazonWebRequest); //should be object, trying to keep it simple
   requests.Add(EBayWebRequest);  //should be object, trying to keep it simple

   foreach (IRequest req in requests)
   {
      responses.Add(req.GetResponse());
   }

   foreach (IResponse resp in response)
   {
      typeof resp????
   }
}

interface IRequest
{
   IResponse GetResponse();
}

interface IResponse
{
}

public class AmazonWebServiceRequest : IRequest
{
   public AmazonWebServiceRequest()
   {
      //get data;
   }

   public IResponse GetResponse()
   {
      AmazonWebServiceRequest request = new AmazonWebServiceRequest();
      return (IResponse)request;
   }
}

public class AmazonWebServiceResponse : IResponse
{
   XmlDocument _xml;
   public AmazonWebServiceResponse(XmlDocument xml)
   {
      _xml = xml;
      _parseXml();
   }

   private void _parseXml()
   {
      //parse Xml into object;
   }
}

public class EBayWebRequest : IRequest
{
   public EBayWebRequest ()
   {
      //get data;
   }

   public IResponse GetResponse()
   {
      EBayWebRequest request = new EBayWebRequest();
      return (IResponse)request;
   }
}

public class EBayWebResponse : IResponse
{
   XmlDocument _xml;
   public EBayWebResponse(XmlDocument xml)
   {
      _xml = xml;
      _parseXml();
   }

   private void _parseXml()
   {
      //parse Xml into object;
   }
}

1 个答案:

答案 0 :(得分:1)

你可以检查这样的类型:

if (resp.GetType() == typeof(AmazonWebRequest))
{
// do something
}
else if (resp.GetType() == typeof(EBayWebRequest))
{
// do something
}

虽然这可能会变得混乱,但如果在接口上添加通用方法来调用任何已实现的类型,例如

,则会更好
resp.Process();

然后在IResponse的每个实现中处理请求的处理。