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 @ 2023-05-10 16:17  _Origin  阅读(11)  评论(0)    收藏  举报