I am building a class library that interacts with various 3rd party API's. I have used an facade pattern to provide simplified access to complicated and confusing calls, and a factory pattern to return the correct implementation. I am now trying to build one of the implementation but cant think of an elegant design.
The implementation i am building requires a URL to be constructed (which i am doing via URIBuilder). I then need to "execute" the url. I then deserialize the Xml result into a class.
I am planning on using HttpClient to call the api with the URI i built, but am not sure on how to structure the class. The options i have thought of are:
A base class of my implementation so can call it via base.InvokeURI(Uri myUri)
.
A seperation class so it can be used by multiple implementations
I am also unsure where the deserialization should reside.
I think using Interface in this case is more suitable:
public interface IURLInvoke
{
string InvokeURI(Uri myUri);
}
// some implementation
public class YourURLInvoker: IURLInvoke
{
public string InvokeURI(Uri myUri)
{
// do something
}
}
public class YourClass
{
public IURLInvoke Invoker {get; set;}
public void InvokeURI(Uri myUri)
{
if(Invoker == null)
return;
string xml = Invoker.InvokeURI(Uri myUri);
// put your code for deserialization here
}
}
// here is an usage example:
YourClass a = new YourClass();
// set an Invoker, choose a strategy to invoke url
a.Invoker = new YourURLInvoker();
a.InvokeURI(url);
This approach is also called Strategy Pattern
Pls see dummy code using adapter pattern and dependency injection. Idea is to create a interface and pass it around
public class Adapter{
public void processRequest(){
RequestProcessor processor = new RequestProcessor();
processor.processRequest();
}
}
public class RequestProcessor{
public void procesRequest(){
Irequest request = new HTTPRequest();
HTTPService service = new HTTPService();
// fetch the uri from builder class
URI url = URIBUIlder();
string response = service.sendRequest(request,url);
// now fetch type from just
Type t = Serializer.searialize<T>(response);
}
}
public Class Serializer{
public static T searialize<T>(string xml){
}
}
public interface IRequest{
public string sendRequest(uri url);
}
public class HTTPRequest:IRequest{
public string sendRequest(uri url){
// instantiate actual http request here and return response
}
}
//This will act as controller
public class HTTPService{
public string sendRequest(IRequest request,uri url) {
return request.sendRequest(url);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.