Sometimes it is necessary to access platform specific APIs, e.g., adding advertisement services or leaderboard functionality provided by frameworks such as .
This can be achieved by allowing specific implementation to be defined through a common API interface; so called interface class.
The following example is pure fiction and assumes we want to use a very simple leaderboard API that is only available on Android. For other targets we simply want to log invocations or provide mock return values.
The first step is to create an abstraction of the API in form of an interface.
The interface is put into the core project (see Project Setup, Running & Debugging):
public void submitScore(String user, int score);
}
Next we create concrete implementations for each platform and put these into their respective projects.
The following would go into the desktop project:
/** Desktop implementation, we simply log invocations **/
public class DesktopLeaderboard implements Leaderboard {
public void submitScore(String user, int score) {
}
}
The following would go into the HTML5 project:
Next, the ApplicationListener
gets a constructor to which we can pass the concrete Leaderboard implementation:
public class MyGame implements ApplicationListener {
private final Leaderboard leaderboard;
this.leaderboard = leaderboard;
}
// rest omitted for clarity