Let's say I'm working with multiple different music stream APIs. User passes me the link from one of the supported streaming services. Similar API responses should be mapped on the same application's object for further processing, but every API has unique algorithm of doing that. What's the correct way of doing that?
I came up with next solution. I'm creating an interface MusicApi
, which contains methods getAppObject
and isLinkMatches
public interface MusicApi {
public static AppObject getAppObject(String link);
public static boolean isLinkMatches(String link);
}
For example we're working with these APIs. Let's say they're implementing method correctly.
public class NapsterApi implements MusicApi {}
public class SpotifyApi implements MusicApi {}
public class YoutubeApi implements MusicApi {} // As example of completely different audio extraction algorithm
Now I have to choose when to use which API. I've decided to create MusicApiSelector
class (Kept implementation listing simple without using Java Reflection API or Spring @Component)
public class MusicApiSelector {
private static final MusicApi[] registeredApis = new MusicApi[]{NapsterApi, SpotifyApi, YoutubeApi};
public static MusicApi getApi(String link) {
for (MusicApi api : registeredApis) {
if (api.isLinkMatches()) {
return api;
}
}
throw new Exception("This link is not supported")
}
}
Using this should look something like this
public class Main {
public static void main(String[] args) {
String link = https://www.youtube.com/watch?v=djV11Xbc914;
MusicApi api = MusicApiSelector.getApi(link);
AppObject appObject = api.getAppObject(link);
}
}
Can you tell me if that's valid approach how this pattern is called (i guess it's Strategy Pattern). And what I can do better (maybe some completely different patterns)
Aucun commentaire:
Enregistrer un commentaire