Create a class according to type identifier

Is there a design template or some other way to create a class by type?

My server receives a json message containing an action to execute.

I have several Action classes that need to be mapped to the corresponding class.

{ TYPE: 'MOVE' ... } => class ActionMove
{ TYPE: 'KILL' ... } => class ActionKill

(All Action classes implement the Action interface).

How to create a class according to type?

+4
source share
3 answers

If you need to keep track of your action instances (i.e. for logs), use the Factory Pattern :

public class ActionFactory{
    public Action createAction(String type){
        if (type.equals("MOVE"))
            return new ActionMove();
        if (type.equals("KILL"))
            return new ActionKill();
        ... // so on for the other types

        return null; //if the type doesn't have any of the expected values
    }
    ...
}
+4
source

Create HashMap display strings for Action objects:

Map<String,Action> map = new HashMap<String,Action>();

map.put("MOVE", new ActionMove());
map.put("KILL", new ActionKill());

And then get the preferred value:

Action a = map.get(type);
a.perform();

.


, , . , , .

+2

OK...

Thanks to your help, I created a Factory method that returns an object according to type.

public class ActionFactory {
public static Action createAction(JSONObject object){

    try{
        String username = object.getString("USERNAME");         
        String type = object.getString("TYPE");
        String src= object.getString("SRC");
        String dest = object.getString("DEST");

        if(type == "MOVE"){
            return new ActionMove(username,src,dest);
        }
        else if(type == "KILL"){
            return new ActionKill(username,src,dest);
        }

        else if(type == "DIED"){
            return new ActionDied(username, src, dest);
        }
        else if(type == "TIE"){
            // TODO: implement
        }
    }
    catch(JSONException e){
        e.printStackTrace();
    }


    return null;

}

}

0
source

Source: https://habr.com/ru/post/1543999/


All Articles