Frage

I am developing a multi player game, which have a module which works on the basis of notifications send by server. For example: Action of other player, score update, action to do etc.

I am receiving notification in json format. I am wondering if there is some codding pattern exist which automatically deliver different notifications to their corresponding handlers. Many thanks for your help.

War es hilfreich?

Lösung

Well, cannot say if this classifies as a pattern:

My take on it would be to simply create a separate class, lets call it JSONGameStateFilter, to filter the JSON object based on the received value plus the state of the game

Something like:

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)
    }
}

The design of this approach would be to implement varies of callbacks on each activity (known pattern for fragments to communicate back to activity).

This is untested and written just now but I am pretty confident that it would work well.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top