'Correct way/design pattern for data transformation
I need to create a REST API proxy-service, which will uniform the response from several other remote REST API services. The remote services have different data formats. The admin of the proxy service should have the ability to switch between different remote services and the response from my service should always be the same.
Does anybody can give me a hint of how this pattern is called and maybe some examples?
Solution 1:[1]
As you should choose an algorithm to handle response, then you can try to use Strategy pattern.
As wiki says about strategy pattern:
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use
Let me show an example.
At runtime, it can be known what response we should handle. So we can choose what object should be instantiated to handle response. For example, you have many responses:
public enum ResponseType
{
One, Two, Three
}
and then yoy should create a base class Response:
public abstract class Response
{
public abstract string Handle();
}
And then you need concrete implementations of this base class Response to transform response to desired type:
public class ResponseOne : Response
{
public override string Handle()
{
return "I am Response One";
}
}
public class ResponseTwo : Response
{
public override string Handle()
{
return "I am Response Two";
}
}
public class ResponseThree : Response
{
public override string Handle()
{
return "I am Response Three";
}
}
Ok, fine. Now we need something like mapper which will be responsible to bring correct instance by selected response type:
public class ResponseFactory
{
public Dictionary<ResponseType, Response> ResponseByType { get; private set; }
= new Dictionary<ResponseType, Response>
{
{ ResponseType.One, new ResponseOne()},
{ ResponseType.Two, new ResponseTwo()},
{ ResponseType.Three, new ResponseThree()},
};
}
and when you will know what response type is, then it is very simple to get correct instance to handle it:
public void HandleResponse(ResponseType responseType)
{
ResponseFactory responseFactory = new ResponseFactory();
Response response = responseFactory.ResponseByType[responseType];
// Here you can use your desired response class
string handledResponse = response.Handle();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | StepUp |
