美文网首页
策略模式

策略模式

作者: 一只小星_ | 来源:发表于2021-05-28 15:19 被阅读0次
    //定义枚举
    public enum TimerBizTypeEnum {
    
        TYPE_ONE(1,"第一种"),
        TYPE_TWO(2,"第二种"),
        TYPE_THREE(3,"第三种");
    
        private int code;
        private String desc;
    
        TimerBizTypeEnum(int code,String desc){
            this.code = code;
            this.desc = desc;
        }
    
        public int getCode(){
            return code;
        }
    
        public String getDesc(){
            return desc;
        }
    
    }
    
    //声明interface
    public interface TimerService {
    
        boolean isMatched(TimerBizTypeEnum typeEnum);
    
        Response getTimerJudger(String param);
    }
    
    //下面是两个实现类举例
    @Service
    public class OneTimerServiceImpl implements TimerService {
    
        @Override
        public boolean isMatched(TimerBizTypeEnum typeEnum) {
            return TimerBizTypeEnum.TYPE_ONE.getCode() == typeEnum.getCode();
        }
    
        @Override
        public Response getTimerJudger(String param) {
            //第一种处理逻辑
            return null;
        }
    }
    
    
    @Service
    public class TwoTimerServiceImpl implements TimerService {
        @Override
        public boolean isMatched(TimerBizTypeEnum typeEnum) {
            return TimerBizTypeEnum.TYPE_TWO.getCode() == typeEnum.getCode();
        }
    
        @Override
        public Response getTimerJudger(String param) {
            //第二种处理逻辑
            return null;
        }
    }
    
    
    
    //下面是加载实现类的manager
    @Service
    public class TimerJudgeManager implements ApplicationContextAware, InitializingBean {
    
        private ApplicationContext applicationContext;
    
        private List<TimerService> services = new ArrayList<>();
    
        public TimerService doGetHandle(TimerBizTypeEnum timerBizTypeEnum){
            for (TimerService service : services){
                if (service.isMatched(timerBizTypeEnum)){
                    return service;
                }
            }
            return null;
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
            for (TimerService service : applicationContext.getBeansOfType(TimerService.class).values()){
                services.add(service);
            }
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    }
    
    
    

    相关文章

      网友评论

          本文标题:策略模式

          本文链接:https://www.haomeiwen.com/subject/ncyssltx.html