Junior — Middle
Have you applied the Factory pattern when working with HTTP requests?
sobes.tech AI
Answer from AI
The Factory pattern is often used for creating HTTP request objects, especially when there is a need to abstract the process of creating different types of requests (GET, POST, PUT, etc.).
For example, you can implement a factory that returns the required request object with preset headers and settings based on parameters:
public interface IHttpRequest
{
void Send();
}
public class GetRequest : IHttpRequest
{
public void Send() { /* implementation of GET request */ }
}
public class PostRequest : IHttpRequest
{
public void Send() { /* implementation of POST request */ }
}
public static class HttpRequestFactory
{
public static IHttpRequest Create(string method)
{
switch(method.ToUpper())
{
case "GET": return new GetRequest();
case "POST": return new PostRequest();
default: throw new ArgumentException("Unsupported method");
}
}
}
// Usage:
var request = HttpRequestFactory.Create("GET");
request.Send();
This approach simplifies the extension and maintenance of the code, allowing centralized management of request creation.