您的位置:首页 > 编程语言 > Java开发

Java中如何消除大量的if else (意面代码)

2018-03-04 12:18 681 查看
参考:

减少该死的 if else 嵌套

java如何消除繁琐的if else 语句?

如何无痛降低 if else 面条代码复杂度

用设计模式来代替臃肿的ifelse层层判断

你还在用if else吗?

如这段读取Excel单元格的代码,看着都烦

try {
for (int j = mainConfig.getContentStartNum(); j <= rowNum; j++) {
row = sheet.getRow(j);
T obj = target.newInstance();
for (int i = 0; i < colNum; i++) {

Field colField = ExcelUtil.getOneByTitle(metaList, titleList[i]);
colField.setAccessible(true);
String fieldType = colField.getType().getSimpleName();
HSSFCell cell = row.getCell(i);
int cellType = cell.getCellType();
System.out.println(colField.getName()+"|"+fieldType+" | "+cellType);

if(HSSFCell.CELL_TYPE_STRING == cellType){
if("Date".equals(fieldType)){
colField.set(obj, DateUtil.parse(cell.getStringCellValue()));
}else {
colField.set(obj, cell.getStringCellValue());
}
}else if(HSSFCell.CELL_TYPE_BLANK == cellType){
System.out.println("字段"+colField.getName());
if("Boolean".equals(fieldType)){
colField.set(obj, cell.getBooleanCellValue());
}else{
colField.set(obj, "");
}
}else if(HSSFCell.CELL_TYPE_NUMERIC == cellType){
if("Integer".equals(fieldType) || "int".equals(fieldType)){
colField.set(obj, (int)cell.getNumericCellValue());
}else {
colField.set(obj, cell.getNumericCellValue());
}
}else if(HSSFCell.CELL_TYPE_BOOLEAN == cellType){
colField.set(obj, cell.getBooleanCellValue());
}
}
result.add(obj);
}
} catch (InstantiationException | IllegalAccessException | ParseException e) {
e.printStackTrace();
}


改造后

private static Map<String, LoadCellValue> handlerMap = new HashMap<>(7);
// 字典结合策略模式简化代码
static{
handlerMap.put("String", new StringHandler());
handlerMap.put("Date", new DateHandler());
handlerMap.put("Boolean", new BooleanHandler());
handlerMap.put("Long", new LongHandler());
handlerMap.put("Integer", new IntegerHandler());
handlerMap.put("Double", new DoubleHandler());
handlerMap.put("Float", new FloatHandler());
}
HSSFCell cell = handlerMap.get(temp.getClass().getSimpleName()).loadValue(row, index, temp);


点击查看Github上的完整源码

- 正如所看到的, 需要新建一堆的处理类, 虽然新增了很多类, 但是职责很明确, 基本符合
对修改关闭对扩展开放
的原则
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: