策略模式-springboot使用Demo

1.生命一個註解 用於標記策略類

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface HandlerReportSubjectType {

    /**
     * 策略類型
     * @return
     */
    int value();
}

2.定義策略接口:

/**
 * 批改報告策略
 */
public interface ReportStrategy {

3.實現策略:

@Slf4j
@Component
@HandlerReportSubjectType(SubjectBo.CH)
public class ChineseReportStrategy implements ReportStrategy {

4.聲明一個map用於收集策略類Bean對象,並實現策略提取方法:

getOrderStrategy(Integer subjectId)
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ReportContext {

    @Autowired
    private ApplicationContext applicationContext;

    public static Map<Integer, Class<ReportStrategy>> reportStrategyBeanMap= new ConcurrentHashMap<>();

    public ReportStrategy getOrderStrategy(Integer subjectId){
        Class<ReportStrategy> strategyClass = reportStrategyBeanMap.get(subjectId);
        if(strategyClass == null) {
            throw new BusinessException("沒有對應的試題批改報告類型");
        }
        return applicationContext.getBean(strategyClass);
    }
}

5.用map收集策略類Bean對象:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 將對應的class初始化到HandlerOrderContext中
 */
@Component
public class HandlerReportProcessor implements ApplicationContextAware {

    /**
     * 獲取所有的策略Beanclass 加入HandlerOrderContext屬性中
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //獲取所有策略註解的Bean
        Map<String, Object> composeStrategyMap = applicationContext.getBeansWithAnnotation(HandlerReportSubjectType.class);
        composeStrategyMap.forEach((k, v) -> {
            Class<ReportStrategy> reportStrategyClass = (Class<ReportStrategy>) v.getClass();
            int type = reportStrategyClass.getAnnotation(HandlerReportSubjectType.class).value();
            //將class加入map中,type作爲key
            ReportContext.reportStrategyBeanMap.put(type, reportStrategyClass);
        });
    }
}

6.具體使用:

        ReportStrategy reportStrategy =  reportContext.getOrderStrategy(insightExamBatch.getSubjectId().intValue());
        return reportStrategy.teacherOverview(batchId, classId, type,insightExamBatch);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章