玩命加载中🤣🤣🤣

SpringBoot使用策略模式Demo


SpringBoot-策略模式Demo

类图

classDiagram
class IStrategy {
	handle() Ret
}
class StrategyImpl1 {
	handle() Ret
}
class StrategyImpl2 {
	handle() Ret
}
class StrategyImpl3 {
	handle() Ret
}
IStrategy <|.. StrategyImpl1 : 实现
IStrategy <|.. StrategyImpl2 : 实现
IStrategy <|.. StrategyImpl3 : 实现

class Context {
	strategyMap : Map~PrjExtractEnum, IExtractPrj~
	Context(Map~String, IExtractPrj~)
}
class StrategyEnum { }

Context o-- IStrategy : 组成
Context <.. StrategyEnum : 依赖

策略接口

IStrategy

public interface IStrategy {
    // 定义规范
    Ret handle(Param param);
}

策略枚举

本模板采用枚举定义每种策略名

public enum StrategyEnum {
    SPRING, SUMMER, AUTUMN, WINTER,
}

环境类

@Service	//将环境类注册至spring容器,形成单例
public class Context {

    private final Map<StrategyEnum, IStrategy> map = new ConcurrentHashMap<>();

    //容器初始化时,spring会将策略类所附属的组件传入进来, 并放入环境类的map中. 注意:spring容器默认是以String作为key
    public Context(Map<String, IStrategy> map) {
        map.forEach((k, v) -> map.put(StrategyEnum.valueOf(k), v)); //注意:此处要通过String映射成策略枚举
    }
    
    //获取具体策略 注意:同样要注意字符串和枚举的转换
    public IStrategy getStrategy(String type) {
        return map.get(StrategyEnum.valueOf(type));
    }
}

具体策略类

@Component("SPRING")
public class StrategyImpl1 implements IStrategy {
	@Override
    public Ret handle(Param param) {
    }
}
...

@Component("SUMMER")
public class StrategyImpl2 implements IStrategy {
	@Override
    public Ret handle(Param param) {
    
    }
}
...

@Component("AUTUMN")
public class StrategyImpl3 implements IStrategy {
	@Override
    public Ret handle(Param param) {
    
    }
}
...

具体使用

@Service
public class XxxServiceImpl implements XxxService {
    @Resource
    private Context context;
    
    @Override
    public Ret toDo(Param param) {
        IStrategy strategy = Optional
                .ofNullable(context.getStrategy(param.getType()))
                .orElseThrow(() -> new RuntimeException("操作类型异常"));
        return strategy.handle(param);
    }
}

文章作者: 👑Dee👑
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 👑Dee👑 !
  目录