策略模式

//定义枚举
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 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;
    }
}


你可能感兴趣的:(策略模式)