/**
* 根据类型生成对应的User子类
* @param type
* @return
*/
public static User createUser(String type) {
if ("A".equals(type)) {
return new AUser();
} else if ("B".equals(type)) {
return new BUser();
} else if ("C".equals(type)) {
return new CUser();
}
}
简单工厂模式往往使用if-else根据传参判断生成相应的实体类(例:createUser方法根据type去创建对应User子类),后期如果新增其它User子类则需扩展else if分支(例:else if ("D".equals(type)) { return new DUser(); }),违反开闭原则,容易出错,影响到已正常运行的程序。
因此我们可以使用枚举+反射来替代这种写法
枚举类
根据传参和子类的类名创建
enum UserEnum{
AUser("A","AUser"),
BUser("B","BUser"),
CUser("C","CUser");
//User类对应的type
private String type;
//User类的类名
private String UserClassName;
//类所属包路径前缀
private