关于Interfacing with platform specific code的译文
这是一个关于这个问题的论坛讨论,还包括iOS的具体内容。
有时,有必要访问平台特定的API,例如添加由诸如Swarm的框架提供的排行榜功能或者广告服务集成。
以下示例假定我们仅在Android上实现非常简单的排行榜API。 对于其他目标平台,我们只需要记录调用或提供模拟返回值。
Android API如下所示:
/** Let's assume this is the API provided by Swarm **/
public class LeaderboardServiceApi {
public void submitScore(String user, int score) { ... }
}
第一步是以接口的形式创建API的抽象。该接口被放入核心项目中:
public interface Leaderboard {
public void submitScore(String user, int score);
}
接下来,我们为每个平台创建具体的实现,并将它们放入各自的项目中。Android项目:
/** Android implementation, can access LeaderboardServiceApi directly **/
public class AndroidLeaderboard implements Leaderboard {
private final LeaderboardServiceApi service;
public AndroidLeaderboard() {
// Assuming we can instantiate it like this
service = new LeaderboardServiceApi();
}
public void submitScore(String user, int score) {
service.submitScore(user, score);
}
}
桌面项目
/** Desktop implementation, we simply log invocations **/
public class DesktopLeaderboard implements Leaderboard {
public void submitScore(String user, int score) {
Gdx.app.log("DesktopLeaderboard", "would have submitted score for user " + user + ": " + score);
}
}
HTML5项目:
/** Html5 implementation, same as DesktopLeaderboard **/
public class Html5Leaderboard implements Leaderboard {
public void submitScore(String user, int score) {
Gdx.app.log("Html5Leaderboard", "would have submitted score for user " + user + ": " + score);
}
}
接下来,ApplicationListener获取一个构造函数,我们可以通过它来传递具体的Leaderboard实现:
public class MyGame implements ApplicationListener {
private final Leaderboard leaderboard;
public MyGame(Leaderboard leaderboard) {
this.leaderboard = leaderboard;
}
// rest omitted for clarity
}
在每个启动类中,我们然后简单地实例化MyGame,将相应的Leaderboard实现作为参数传递,例如在桌面上:
public static void main(String[] argv) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
new LwjglApplication(new MyGame(new DesktopLeaderboard()), config);
}