关于设计模式-策略模式
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; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)