方法代码取决于Instance的值?

时间:2014-04-15 16:18:16

标签: java android class interface command-pattern

我对Android(Java)有疑问。

假设我有一个命令列表(每个命令都带有命令名和执行方法) 执行方法根据命令名称具有不同的代码(即命令" GET GPS LOCATION" - >执行方法返回位置值)。

因此,我可以在execute方法中使用带有switch-case的单个Command类来检查命令的名称并执行代码。
或者为每个命令创建一个类(这不是我猜的最佳方式,因为我有80多个命令) 或者我应该使用界面?
或者有更好的方法吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

从Java8开始,您可以使用method references以简洁的方式执行此操作:

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() {

  }
}

然后,调用map.get(methodName).run()就足够了。

答案 1 :(得分:0)

如何创建一个抽象的Command类并使用map来检索正确的命令,例如:

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

然后实施:

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

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

然后您可以像这样检索它们:

public static void main(String[] args)
{
    new LocationCommand();
    Command.commands.get("GET GPS LOCATION").execute(); //Output: Getting GPS location
}