1 前言
在日常开发中,可能会遇到多重if else的情况,而且后期会随着业务发展不断的增加不同类型的逻辑,但是他们的入参和出参是一致的。那么,可以采用策略模式+工厂模式去实现。但是,如果只是单纯的策略模式+工厂模式的话,每一次增加新的逻辑都需要去改动业务代码,这时候可以增加一个枚举,在策略工厂中去遍历初始化策略,就可以做到无侵入业务代码。
2 具体实现代码
1、策略接口
public interface IStartegy{
void run(String test);
}
2、实现策略接口类
public class Startegy1 implements IStartegy{
@Override
public void run(String test) {
// 你的代码
}
}
3、枚举类
public enum StartegyEnum {
STRATEGY_1("STRATEGY_1","com.xxx.Startegy1"),
STRATEGY_2("STRATEGY_2","com.xxx.Startegy2"),
;
private String type;
private String className;
DataCheckFilterEnum(String type, String className) {
this.type = type;
this.className = className;
}
public String getType() {
return type;
}
public String getClassName() {
return className;
}
}
4、策略工厂
@Slf4j
public class StrategyFactory {
private static Map<String, IStrategy> map = new HashMap<>();
static {
for (StartegyEnum enum: StartegyEnum.values()) {
try {
Class<?> clazz = Class.forName(enum.getClassName());
IStrategy iStrategy = (IStrategy) clazz.newInstance();
map.put(enum.getType(), iStrategy);
} catch (ClassNotFoundException e) {
log.error(e.getMessage(), e);
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
} catch (InstantiationException e) {
log.error(e.getMessage(), e);
}
}
}
public static IStrategy getIStrategy(String type) {
return map.get(type);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71364.html