此文转载自:https://blog.csdn.net/yqq962464/article/details/110228633
基于反射的工厂模式
基础枚举类:
/**
* @author: yangyahui
* @Date: 2020/11/11 9:52 上午
* @Description: 惠农业务品种
*/
public enum BusinessTypeEnum {
CHD("12020020140","彩虹贷"),
JQD("12020020130","金秋贷"),
NXD("16020040400","农兴贷"),
ZND_JY("12020020020","助农贷(农户经营"),
ZND_XF("12020010050","助农贷(农户消费"),
XMD("12020020030","农户畜牧业养殖贷款");
private String code;
private String desc;
BusinessTypeEnum(String code,String desc){
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static BusinessTypeEnum getType(String code){
for (BusinessTypeEnum typeEnum : values()){
if (typeEnum.getCode().equals(code)){
return typeEnum;
}
}
return null;
}
}
简单工厂类:
public static FreeBaseDetailVO buildFreeObj(String businessType){
FreeBaseDetailVO freeBaseDetailVO = null;
switch (BusinessTypeEnum.getType(businessType)) {
case CHD:
freeBaseDetailVO = new FreeCHDDetailVO();
break;
case JQD:
freeBaseDetailVO = new FreeJQDDetailVO();
break;
case NXD:
freeBaseDetailVO = new FreeNXDDetailVO();
break;
case ZND_JY:
freeBaseDetailVO = new FreeZNDJYDetailVO();
break;
case ZND_XF:
freeBaseDetailVO = new FreeZNDXFDetailVO();
break;
case XMD:
freeBaseDetailVO = new FreeXMDDetailVO();
break;
default:
throw new RuntimeException("全流程返回业务品种码值错误:" + businessType);
}
return freeBaseDetailVO;
}
改造:由于不满足“开闭原则”,所以对工厂类进行改造,通过引入配置文件和反射,使之满足“开闭原则”。
/**
* @author: yangyahui
* @Date: 2020/11/27 10:52 上午
* @Description: 读取配置文件参数工具类
*/
public class PropertiesUtil {
private static Map<String, Properties> cacheMap = new HashMap<String, Properties>();
public static String get(String fileName, String key){
return (String) getProperties(fileName).get(key);
}
private static Properties getProperties(String fileName){
if (cacheMap.get(fileName) != null){
return cacheMap.get(fileName);
}
InputStream is = PropertiesUtil.class.getResourceAsStream(fileName);
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
cacheMap.put(fileName,properties);
return properties;
}
}
/**
* @author: yangyahui
* @Date: 2020/11/27 11:02 上午
* @Description: 工厂类
*/
public class Factory {
public static FreeBaseDetailVO getObj(String fileName,String key){
FreeBaseDetailVO freeBaseDetailVO = null;
String classPath;
try {
classPath = PropertiesUtil.get(fileName, key); //获取配置文件中的类路径
if (StringUtils.isNotBlank(classPath)){
freeBaseDetailVO = (FreeBaseDetailVO) Class.forName(classPath).newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
return freeBaseDetailVO;
}
}
配置文件配置信息application.properties
CHD = com.hrbank.entity.vo.freenong.FreeCHDDetailVO