策略模式优化过多的if else 代码

策略模式-应用

利用反射+策略模式优化过多的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执行不同的策略
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值