请参阅下面的代码.这里基于String常量,我实例化了不同类型的组件类.现在至少有15种不同类型的String常量.因此,如果我遵循这种模式,将有15种不同的情况和那些很多if -else块.有没有更好的方法呢?我想通过尽可能少的代码更改来灵活地添加和删除案例.
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;
}
Run Code Online (Sandbox Code Playgroud)
PS:我们正在使用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();
}
Run Code Online (Sandbox Code Playgroud)
这种方法的IFs
优点在于它取代了多态性(在我的意见中是非常OO).
对不起,我刚才意识到你有一个默认类型(代码中的最后一个),所以你可能需要添加一个if
地方:(.
归档时间: |
|
查看次数: |
229 次 |
最近记录: |