public interface Strategy { /** * 调用策略方法 * @param strategyParam 执行策略方案参数 * @return 业务处理返回结果封装实体 */ AjaxResult invokeStrategy(StrategyParam strategyParam); /** * 获取当前对象对应枚举 * @return 策略枚举 */ StrategyEnum getStrategyEnum(); }
/** * @author YUFEI * @Date 2022/9/19 9:11 * @Version 1.0 */ @Service(value = "strategyA") @BusinessStrategy public class StrategyA implements Strategy { @Override public AjaxResult invokeStrategy(StrategyParam strategyParam) { System.out.println("正在执行StrategyA......"); return null; } @Override public StrategyEnum getStrategyEnum() { return StrategyEnum.STRATEGY_A; } }
@Service(value = "strategyB") @BusinessStrategy public class StrategyB implements Strategy { @Override public AjaxResult invokeStrategy(StrategyParam strategyParam) { System.out.println("正在执行StrategyB......"); return null; } @Override public StrategyEnum getStrategyEnum() { return StrategyEnum.STRATEGY_B; } }
@Component public class StrategyContext { public static MapstrategyMap = new ConcurrentHashMap<>(16); /** * 执行策略上下文 * @param strategyParam 策略参数 * @return 业务处理返回封装实体 */ public AjaxResult invokeContext(StrategyParam strategyParam){ if (strategyParam == null){ throw new IllegalArgumentException("执行策略参数不能为空"); } // 获取策略参数中枚举实例 StrategyEnum strategyEnum = strategyParam.getStrategyEnum(); // 通过枚举实例Get对应策略类 Strategy strategy = strategyMap.get(strategyEnum); if(strategy==null){ throw new IllegalArgumentException("策略实现类不存在"); } // 执行策略方案 return strategy.invokeStrategy(strategyParam); } }
import com.cdkj.common.enums.StrategyEnum; import com.cdkj.framework.annotation.BusinessStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.stereotype.Component; /** * 策略类管理器 * @author ChenErGao */ @Component public class StrategyManage implements BeanPostProcessor { private final static Logger log = LoggerFactory.getLogger(StrategyManage.class); @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // 一定要将Bean实例返回 return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // 判断Bean是否被自定义注解标示 if (bean instanceof Strategy && bean.getClass().isAnnotationPresent(BusinessStrategy.class)){ // 将策略类强转为顶层策略接口 Strategy strategy = (Strategy) bean; StrategyEnum strategyEnum= strategy.getStrategyEnum(); if(strategyEnum==null){ log.warn("######[StrategyManage]#################"); } // 将策略类添加到策略Map中 StrategyContext.strategyMap.put(strategy.getStrategyEnum(), strategy); } // 一定要把Bean实例返回 return bean; } }
/** * @author YUFEI * @Date 2022/9/19 9:11 * @Version 1.0 */ public class StrategyParam { StrategyEnum strategyEnum; public StrategyEnum getStrategyEnum() { return strategyEnum; } public void setStrategyEnum(StrategyEnum strategyEnum) { this.strategyEnum = strategyEnum; } }