我有这段代码:
@Override
public void inform(String data) {
if (data.equals(C.SubscriptionEvents.WINDOW_CLOSED)) {
File tempFolder = new File("temp");
File[] files = tempFolder.listFiles();
if (files != null) {
for (File f : files) f.delete();
}
} else if (data.equals(C.Controller.Commands.SELECT_MODE_VERTICES)) {
MainModel.setCurrentMode(Mode.VERTICES);
display.getInfoSection().repaint();
} else if (data.equals(C.Controller.Commands.SELECT_MODE_LINES)) {
MainModel.setCurrentMode(Mode.LINES);
display.getInfoSection().repaint();
} else if (data.equals(C.Controller.Commands.SELECT_MODE_SECTORS)) {
MainModel.setCurrentMode(Mode.SECTORS);
display.getInfoSection().repaint();
}
}
该方法获取一个字符串,它是命令名称。根据名称,它会执行指定的行为。正如您所看到的,它开始有太多的 elseif(并且可能会有更多)。该方法属于在包之间共享的接口(interface),因此我决定将参数设置为字符串。 有没有更好的方法来避免当有大量命令时方法变得庞大(这也包括 switch case)?
最佳答案
您可以检查Command
模式https://www.baeldung.com/java-command-pattern但它可能需要相当广泛的重构,并使方法 inform()
接受 Command
关于java - 用更通用的方式替换 elseif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52226910/