所以我從 twitch irc 收到一個字符串,并根據該命令執(zhí)行一些代碼。問題是我可以簡化我的代碼或使用模式。問題是大多數(shù)命令具有相同的代碼,只有回復發(fā)生了變化。你可以看到下面的代碼。它看起來很亂,添加新命令或功能可能會很痛苦(如果我有 200 個或更多命令),而且大部分代碼都是相同的。public void onCommand(User user, Channel channel, String command) { // some if statements switch (command.toLowerCase()){ case "hi":{ //some simple action } case "fire":{ vote(60, channel, "fire") } ... //timeout } void vote(int duration, final Channel channel, String voteFor){ Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { //start voting }, duration); switch (voteFor){ case "fire":{ if (voteYes > voteNo) { //some action }else //some action break; } ... } PS 我嘗試使用策略模式,但感覺沒有必要。
2 回答

搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
使用地圖:
class CommandProcessor {
interface Command {
String executeForKey();
void execute(User user, Channel channel);
}
class OnFireCommand implements Command {
public String executeForKey() { return "fire"; }
public void execute() {}
}
Map<String, Command> map = new HashMap<>();
CommandProcessor() {
// this will become a simple listing of commands
put(new OnFireCommand())
}
void put(Command c) {
map.put(c.executeForKey(), c);
}
public void onCommand(User user, Channel channel, String command) {
this.map.get(command).execute(user, channel);
}
}
添加回答
舉報
0/150
提交
取消