Reputation: 4682
I have been working on an API which is based on Laravel framework in PHP, but this is not specific to the language. There is a number of third party APIs are used here in the API and have a number of multiple configurations. So I would like to create an HTTP client factory class, and in the code, I am planning to create an object for this and passing the API name as a parameter. The main issue is how can I resolve this to various classes according to the name of particular API? That is when I give Google, it needs to initialize the Google class and return the Google API client and for other APIs, it should respond with the corresponding client.
I have a confusion like this is a right use case for factory pattern and if it is not, is there any other patterns or standard methods for doing this instead of calling each of the API clients separately.?
Upvotes: 5
Views: 3419
Reputation: 1867
Here, you need to use a combination of Factory Method and Adapter pattern. Factory method will create your native API classes' objects(e.g. Google, etc.) and adapter will provide you a common interface. So basically you do the following:
Below is the sample code.This is using C#. You can do some modification of below code.
public interface IApiAdapter
{
void Read(int id);
void Write(string data);
}
public class GoogleApiAdapter : IApiAdapter
{
private GoogleApiClass _googleApiClass;
public void Read(int id)
{
//some additional work
//call google api
_googleApiClass.readSomeData(id);
}
public void Write(string data)
{
//some additional work
//call google api
_googleApiClass.writeSomeData(data);
}
}
public class FacebookApiAdapter : IApiAdapter
{
private FacebookApiClass _facebookApiClass;
public void Read(int id)
{
//some additional work
//call facebook api
_facebookApiClass.readSomeData(id);
}
public void Write(string data)
{
//some additional work
//call facebook api
_facebookApiClass.writeSomeData(data);
}
}
public class ApiFactory
{
public static IApiAdapter GetApiFactory(string type)
{
if(type == "google")
{
return new GoogleApiAdapter();
}
if(type == "facebook")
{
return new FacebookApiAdapter();
}
}
}
//calling code
IApiAdapter api = ApiFactory.GetApiFactory("google");
api.Read(2);
Upvotes: 8