【发布时间】:2011-05-20 09:53:35
【问题描述】:
代码是
public interface Command {
public Command[] parseCommand(String command);
}
public enum CameraCommand implements Command {
CLICK;
public Command[] parseCommand(String commands) {
if ("CLICK".equals(commands))
return new Command[] { CameraCommand.CLICK };
return null;
}
}
public enum RoverCommand implements Command {
L,
R,
M;
public Command[] parseCommand(String commandString) {
RoverCommand[] commands = new RoverCommand[commandString.length()];
for (int i = 0; i < commandString.length(); i++) {
switch (commandString.charAt(i)) {
case 'L':
commands[i] = RoverCommand.L;
break;
case 'R':
commands[i] = RoverCommand.R;
break;
case 'M':
commands[i] = RoverCommand.M;
break;
default:
break;
}
}
return commands;
}
}
我这样做是为了对命令类型进行分组。 现在的问题是,我得到一个特定类型的字符串命令,例如“CLICK”。我不知道类型,但我希望这样做
Machine machine = getMachine(type); //machine is an interface, i pass type and get a typeof machine
//machine.parseCommand(commandString); //i don wish to have this logic inside the machine
Command[] command = Command.parseCommand(commandString); // this didnt work, how to solve this, work around?
machine.execute(command); ///finally pass the command and execute the action
任何帮助将不胜感激
谢谢 V
【问题讨论】:
-
这里没有问题。请确保当您在 Stackoverflow 上提问时,您实际上在某处包含问号
标签: java interface enums abstraction