Question

I have a question for Android (Java).

Lets say i have a list of commands (each one with command name, and execute method).
The execute method has different code depending on the command name (i.e. Command "GET GPS LOCATION" -> execute Method returns Location value).

So, I could use a single Command class with a switch-case in the execute method checking the name of the command and executing the code.
Or make a class for every command (which is not the best way i guess, because i have 80+ commands).
Or should i use an interface?
Or is there a better way at all?

Thanks for your help!

Was it helpful?

Solution

Since Java8, you can use method references to do this in a concise way :

public class Test {

  Map<String, Runnable> map = Maps.newHashMap();
  map.put("foo", Test::foo);
  map.put("bar", Test::bar);

  public static void foo() {

  }


  public static void bar() {

  }
}

Then, calling map.get(methodName).run() is enough.

OTHER TIPS

How about you make an abstract Command class and use a map to retrieve the correct command, for example:

abstract class Command<T>
{
    public static final Map<String, Command> commands = new HashMap<>();

    public Command(final String executeCommand)
    {
        commands.put(executeCommand, this);
    }

    public abstract T execute();
}

Then implemented with:

class LocationCommand extends Command<LocationValue>
{
    public LocationCommand()
    {
        super("GET GPS LOCATION");
    }

    @Override
    public LocationValue execute()
    {
        System.out.println("Getting GPS location");
        return null;
    }
}

Then you could retrieve them like so:

public static void main(String[] args)
{
    new LocationCommand();
    Command.commands.get("GET GPS LOCATION").execute(); //Output: Getting GPS location
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top