gpt4 book ai didi

java - 这段代码可以用更好更灵活的方式编写吗?

转载 作者:行者123 更新时间:2023-12-01 03:56:10 26 4
gpt4 key购买 nike

请看下面的代码。这里基于String常量,我实例化了不同类型的组件类。现在至少有 15 种不同类型的字符串常量。因此,如果我遵循这种模式,将会有 15 种不同的情况和许多 if -else block 。有更好的方法吗?我希望能够通过进行尽可能少的代码更改来灵活地添加和删除案例。

public UIComponent initCellEditor(String editorType) {
UIComponent editControl = null;
if ("TbComboBoxCellType".equals(editorType)) {
editControl = new WebListEntryField();
editControl.setId("ComboBox");
} else if ("TbStringCellType".equals(editorType)) {
editControl = new WebInputEntryField();
editControl.setId("String");
} else if ("TbDateCellType".equals(editorType)) {
editControl = new WebDateEntryField();
editControl.setId("Date");
} else if ("TbDateTimeCellType".equals(editorType)) {
editControl = new WebDateTimeEntryField();
editControl.setId("DateTime");
} else {
//default editor is allways a text input
editControl = new WebInputEntryField();
editControl.setId("Input");
}
return editControl;
}

P.S:我们使用的是 JDK 6。所以不能使用 switch on String 特性。

最佳答案

例如,您可以将这些字符串常量转换为枚举,并在枚举上添加构建器方法

public enum CellType {
TbComboBox {
@Override
public UIComponent newComponent() {
return new xxx();
}
},
TbDate {
@Override
public UIComponent newComponent() {
return new xxx();
}
}

public abstract UIComponent newComponent();
}

这种方法的美妙之处在于它用多态性(在我看来这是非常面向对象的)取代了 IFs


抱歉,我刚刚意识到您有一个默认类型(代码中的最后一个 else),因此您可能需要在某处添加一个 if :(。

关于java - 这段代码可以用更好更灵活的方式编写吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12474437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com