策略模式-应用
利用反射+策略模式优化过多的if else 代码
注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface HandlerType {
String value();
}
策略抽象类
public abstract class AbstractStategy {
public abstract void handle();
}
策略具体实现
@Component
@HandlerType("useAStrategy")
public class StrategyA extends AbstractStategy {
@Override
public void handle() {
System.out.println("使用A策略");
}
}
@Component
@HandlerType("useBStrategy")
public class StrategyB extends AbstractStategy {
@Override
public void handle() {
System.out.println("使用B策略");
}
}
策略上下文
@Component
public class StrategyContext implements ApplicationRunner {
@Autowired
private ApplicationContext applicationContext;
private Map<String,Class> map = new HashMap<>();
public void handle(String type) {
Class clazz = map.get(type);
if (clazz==null) //不存在该策略
return;
AbstractStategy stategy=(AbstractStategy)applicationContext.getBean(clazz);
stategy.handle();
}
private void init(String packageName){
URL url = this.getClass().getClassLoader().getResource(packageName.replace(".","/"));
File dir = new File(url.getFile());
for (File file : dir.listFiles()){
if (file.isDirectory()){
// 递归扫描子目录
init(packageName + "." + file.getName());
}else {
String clazzName = packageName + "." + file.getName().replace(".class","");
try {
Class<?> clazz = Class.forName(clazzName);
if (clazz.isAnnotationPresent(HandlerType.class)){
// 获取策略名
HandlerType annotation = clazz.getAnnotation(HandlerType.class);
// 将扫描到的策略放入容器
map.put(annotation.value(),clazz);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run(ApplicationArguments args) throws Exception {//应用服务启动时,运行该方法
this.init("com.spring.springMVC.strategy_pattern.strategy.impl");//策略实现类所在的包名
}
}
将策略上下文注入要用的Service
@Service
public class MyService {
@Autowired
StrategyContext strategyContext;
public void get(String type) {
strategyContext.handle(type);//StrategyContext根据不同的type执行不同的策略
}
}