這是一個關于這個問題的論壇討論,還包括iOS的具體內容绝淡。
有時宙刘,有必要訪問平臺特定的API,例如添加由諸如Swarm的框架提供的排行榜功能或者廣告服務集成牢酵。
以下示例假定我們僅在Android上實現(xiàn)非常簡單的排行榜API悬包。 對于其他目標平臺,我們只需要記錄調用或提供模擬返回值馍乙。
Android API如下所示:
/** Let's assume this is the API provided by Swarm **/
public class LeaderboardServiceApi {
public void submitScore(String user, int score) { ... }
}
第一步是以接口的形式創(chuàng)建API的抽象布近。該接口被放入核心項目中:
public interface Leaderboard {
public void submitScore(String user, int score);
}
接下來,我們?yōu)槊總€平臺創(chuàng)建具體的實現(xiàn)丝格,并將它們放入各自的項目中撑瞧。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實現(xiàn):
public class MyGame implements ApplicationListener {
private final Leaderboard leaderboard;
public MyGame(Leaderboard leaderboard) {
this.leaderboard = leaderboard;
}
// rest omitted for clarity
}
在每個啟動類中预伺,我們然后簡單地實例化MyGame,將相應的Leaderboard實現(xiàn)作為參數傳遞曼尊,例如在桌面上:
public static void main(String[] argv) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
new LwjglApplication(new MyGame(new DesktopLeaderboard()), config);
}