先对贫血的工具类做个解释:没有面向对象多态体现的工具类,这些工具类都是贫血的,只能满足单一需求的工具类,如下:
public class BOValueTransferUtil { public static DimValueVO createDimValue(String value, String title) { DimValueVO dimValueVO = new DimValueVO(); dimValueVO.setValue(value); dimValueVO.setTitle(ImmutableMap.of(CurrentUserUtils.getCurrentLanguageCode(),title)); return dimValueVO; } public static BOValueObjectVO createDimValue(String value, String title, BOColumnDataTypeEnum dataType) { DimValueVO dimValueVO = new DimValueVO(); dimValueVO.setValue(value); dimValueVO.setTitle(ImmutableMap.of(CurrentUserUtils.getCurrentLanguageCode(),title)); return BODataUtils.createValue(dimValueVO,dataType); } public static BOValueObjectVO createDimValue(String objectId, BOColumnDataTypeEnum dataType) { return BODataUtils.createValue(BillDataUtils.createDimValue(CurrentUserUtils.getCurrentLanguageCode(), objectId), dataType); } }
这些入参都是具体类型的参数,只能满足具体类型的参数传入。难道就没有更好的写法,满足各式各样的需求吗?对于下面代码,第二个入参是接口,如果需求不同,那就实现接口吧。
public static BOUpdateUtilVO createBOUpdateUtilVO(String tableName, BOUpdateUtilVOHandler boUpdateUtilVOHandler) { BOUpdateUtilVO boUpdateUtilVO = new BOUpdateUtilVO(); boUpdateUtilVO.setTableName(tableName); Map<String, Object> condition = new HashMap<>(); Map<String, Object> targetFieldDataMap = new HashMap<>(); boUpdateUtilVOHandler.handle(condition, targetFieldDataMap); boUpdateUtilVO.setTargetFieldDataMap(targetFieldDataMap); boUpdateUtilVO.setCondition(condition); return boUpdateUtilVO; } /** * 创建BOUpdateUtilVO实例的回调,设置condition, targetFieldDataMap */ public interface BOUpdateUtilVOHandler { void handle(Map<String, Object> condition, Map<String, Object> targetFieldDataMap); }
熟知设计模式的开发人员,明显看出使用了模板模式的变种:回调。好处自己体会。