所以我从 twitch irc 收到一个字符串,并根据该命令执行一些代码。问题是我可以简化我的代码或使用模式。问题是大多数命令具有相同的代码,只有回复发生了变化。你可以看到下面的代码。它看起来很乱,添加新命令或功能可能会很痛苦(如果我有 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
提交
取消