240
世界上有2种人,一种懂二进制,另一种不懂二进制。

关于设计模式-策略模式

UML图:

 

描述:  设计模式系列中分类为行为型模式的一种,通过把不同处理逻辑封装为策略对象,然后在代码逻辑中通过 context 上下文对象来选择合适的策略对象处理事物

实现方案:  1.SpringBean 自动注入 context 上下文对象,可以获取到所有策略对象,

      2.策略对象通过 key-value 方式保存到 static 静态的 map 对象中,根据 key 决定使用哪个策略

代码实现:

 

复制代码
/**
 * 一.Context 类:  1.策略模式环境上下文
 *          2.加载已有策略 提供获取策略对象方法
 * @author Seven
 */
@Component
public class ExampleStrategyContext{
    /**
     * 通过Spring自动注入功能获取到所有实现ExampleStrategy接口的Bean对象
     */
    @Autowired
    Map<String, ExampleStrategy> strategys = new ConcurrentHashMap<String, ExampleStrategy>(3);

    /**
     * 静态方法方便非SpringBean对象方法中调用
     * @param
     * @return
     */
    public  ExampleStrategy getStrategyService(@NotNull String component){
        ExampleStrategy strategy = strategys.get(component);
        if(strategy == null) {
            throw new RuntimeException("no strategy defined");
        }
        return strategy;
    }

    /**
     * 调用具体策略业务逻辑方法
     */
    public String doSomething(@NotNull String component){

        return getStrategyService(component).doSomething();
    }
}
复制代码

 

public interface ExampleStrategy {
    /**
     * 代表具体业务逻辑方法
     */
    String doSomething();
}
复制代码
@Component("one")
public class ExampleStrategy1 implements ExampleStrategy{

    @Override
    public String doSomething() {
        System.out.println("one策略的具体实现");
        return "one";
    }
}
复制代码
复制代码
@Component("two")
public class ExampleStrategy2 implements ExampleStrategy{

    @Override
    public String doSomething() {
        System.out.println("two策略的具体实现");
        return "two";
    }
}
复制代码
复制代码
    @Resource
    ExampleStrategyContext exampleStrategyContext;

    @PostMapping("/strategy")
    @ApiOperation("不同的策略类型调用对应的策略")
    public String strategy(@RequestParam("key") String key) {
        String result;
        try {
            result = exampleStrategyContext.doSomething(key);
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }
复制代码

 

posted @   _Origin  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示