Search code examples
javaandroidclassinterfacecommand-pattern

Method code depending on value of Instance?


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!


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.