葉氏,看起來像一個Command + Prototype模式給我。
在命令中你定義了要做什麼,原型是將每個命令的一個實例放在一個查找表中,並「克隆」它們以便每次執行。
的重構將是這樣的:
前:
public void handleParsedCommand(String[] commandArr) {
if(commandArr[0].equalsIgnoreCase("message")) {
int target = Integer.parseInt(commandArr[1]);
String message = commandArr[2];
MachatServer.sendMessage(target, this.conId, message);
} else if(commandArr[0].equalsIgnoreCase("quit")) {
// Tell the server to disconnect us.
MachatServer.disconnect(conId);
} else if(commandArr[0].equalsIgnoreCase("confirmconnect")) {
// Blah blah and so on for another 10 types of command
} else {
try {
out.write("Unknown: " + commandArr[0] + "\n");
} catch (IOException e) {
System.out.println("Failed output warning of unknown command.");
}
}
}
後:
public void handleParsedCommand(String[] commandArr) {
Command.getCommand(commandArr).execute();
}
// Define the command and a lookup table
abstract class Command {
// Factory using prototype
public static Command getCommand(String [] commandArr) {
// find the handling command
Command commandPrototype = commandMap.get(commandArr[0]);
// if none was found, then use "uknown"
if (commandPrototype == null) {
commandPrototype = commandMap.get("unknown");
}
// Create an instance using clone
Command instance = commandPrototype.clone();
instance.args = commanrArr;
return instance;
}
// lookup table (switch substitute)
private static Map<String,Command> commandsMap = new HashMap()<String,Command>(){{
put("message" , new MessagCommand());
put("quit" , new QuitCommand());
put("confirmconnect", new ConfirmConnectCommand());
...
put("unknow" , new UnknownCommand());
}};
// args of the command
private String [] args;
public void execute();
String [] getArgs(){
return this.args;
}
}
而且提供的具體實現
class MessageCommand extends Command {
public void execute(){
int target = Integer.parseInt(commandArr[1]);
String message = commandArr[2];
MachatServer.sendMessage(target, this.conId, message);
}
}
class MessageCommand extends Command {
public void execute(){
int target = Integer.parseInt(getArgs()[1]);
String message = getArgs()[2];
MachatServer.sendMessage(target, this.conId, message);
}
}
class QuitCommand extends Command {
public void execute() {
MachatServer.disconnect(conId);
}
}
class ConfirmConnectCommand extends Command {
public void execute() {
/// blah blah blah
}
}
class UnknowCommand extends Command {
public void execute() {
try {
out.write("Unknown: " + commandArr[0] + "\n");
} catch (IOException e) {
System.out.println("Failed output warning of unknown command.");
}
}
}
// ... other 10 implementations here...
的Java的什麼版本? SWITCH是*最後*在最新的(或已經發布了嗎?)版本中支持字符串.. – 2009-10-19 17:45:26
它是Java 6。 。 – Macha 2009-10-19 17:48:19
也許http://stackoverflow.com/questions/1199646/long-list-of-if-statements-in-java/1199677與此相關? – dfa 2009-10-19 18:31:15