我正在开发一个多人游戏,它有一个基于服务器发送通知的模块。例如:其他玩家的动作、分数更新、待办事项等。
我收到 json 格式的通知。我想知道是否存在一些编码模式,它会自动将不同的通知传递给它们相应的处理程序。非常感谢您的帮助。
我正在开发一个多人游戏,它有一个基于服务器发送通知的模块。例如:其他玩家的动作、分数更新、待办事项等。
我收到 json 格式的通知。我想知道是否存在一些编码模式,它会自动将不同的通知传递给它们相应的处理程序。非常感谢您的帮助。
好吧,不能说这是否归类为模式:
我的看法是简单地创建一个单独的类,我们称之为 JSONGameStateFilter,根据接收到的值加上游戏状态来过滤 JSON 对象
就像是:
public class JSONGameStateFilter() {
public interface GameInterface1 {
// callback methods for activity 1
// example: public void newPlayerArrived(String name, int score);
// ...
}
public interface GameInterface2 {
// callback methods for activity 2
}
public interface GameInterface3 {
// callback methods for activity 3
}
private GameInterface1 callback1;
private GameInterface2 callback2;
private GameInterface3 callback3;
private JSONGameStateFilter instance;
public static JSONGameStateFilter getInstance() {
if (instance != null) {
return instance = new JSONGameStateFilter();
}
}
private JSONGameStateFilter() {}
public void registerListener(GameInterface1 callback) {
// called by Activity1 implementing GameInterface1
// by JSONGameStateFilter.newInstance().registerListener(this);
this.callback1 = callback;
}
public void registerListener(GameInterface2 callback) {
this.callback2 = callback;
}
public void registerListener(GameInterface3 callback) {
this.callback3 = callback;
}
public void filterJSON(JSONObject object) {
// read JSON and gamestate
// depending on situation call the right callback
// example: if (callback1 != null) callback1.newPlayerArrived(name, score)
}
}
这种方法的设计是在每个活动上实现不同的回调(片段与活动通信的已知模式)。
这是未经测试和刚刚编写的,但我非常有信心它会很好地工作。