开发者

IRequest / IResponse Pattern

I am trying to create an Interface-based Request/Response pattern for Web API requests to allow for asynchronous consumer/producer processing, but not sure how I would know what the underlying IResponse class is.

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

interf开发者_StackOverflow中文版ace 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;
   }
}


You can check the type like this:

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

This can get messy though, it's better if you add a generic method on the interface to call for any implemented type, like

resp.Process();

Then handle the processing of the request inside each implementation of IResponse.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜