java - 用更通用的方式替换 elseif

标签 java if-statement switch-statement

我有这段代码:

@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/

相关文章:

java - 如何检测包含任意字符串的模式?

java - 更改区域设置操作会导致 404

java - (编译器) else if(true) vs else 场景

javascript - 为 Javascript 切换 css 被禁用

java - HttpResponse 仅显示来自 Java 应用程序的 404 错误,而不显示来自网站的 404 错误

java - DefaultTreeModel 和 Wicket 树 : setAsksAllowsChildren doesn't work

java - 一个类中的方法与另一类中的方法交互时出现问题

if-statement - Haskell 函数返回列表中出现次数超过给定数量的元素列表

c - 错误 : case label does not reduce to an integer constant when using character data type

Golang - 未在转换为 float64 的接口(interface)上定义的比较运算符