Spring Boot 实现策略模式
转载自 微信公众号 [
]策略模式和工厂模式相信大家都比较熟悉,但是大家有没有在springboot中实现策略和工厂模式?
具体策略模式和工厂模式的UML我就不给出来了,使用这个这两个模式主要是防止程序中出现大量的IF ELSE IF ELSE....
。接下来咱们直接实现,项目结构图:
工厂类FactoryStrategy
负责创建策略的工厂,代码比较简单,比较关键的一点是AutoWired
一个Map<String, Strategy>
这个会在初始化的时候将所有的Strategy
自动加载到Map
中,是不是很方便。使用concurrentHashMap
是防止多线程操作的时候出现问题。同时还要注意@Service
注解。
package com.hqs.pattern.factory; import com.hqs.pattern.strategy.Strategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @Date 2019-01-31 */ @Service public class FactoryForStrategy { @Autowired Map<String, Strategy> strategys = new ConcurrentHashMap<>(3); public Strategy getStrategy(String component) throws Exception{ Strategy strategy = strategys.get(component); if(strategy == null) { throw new RuntimeException("no strategy defined"); } return strategy; } }
接下来就是Strategy
接口,就一个doOperation
方法。
package com.hqs.pattern.strategy; /** * @Date 2019-01-31 */ public interface Strategy { String doOperation(); }
定义接口的实现,我定义了三个, 都类似,这里我就放出一个来吧。Component
里边的one
是指定其名字,这个会作为key
放到Map strategys
里边。
package com.hqs.pattern.strategy.impl; import com.hqs.pattern.strategy.Strategy; import org.springframework.stereotype.Component; /** * @Date 2019-01-31 */ @Component("one") public class StrategyOne implements Strategy { @Override public String doOperation() { return "one"; } }
好了,写一个Controller
类,用于进行测试,当然我还是使用swagger
,使用swagger
的时候有个细节,就是注意生产上一定不能打开,否则是个非常可怕的事情。
package com.hqs.pattern.controller; import com.hqs.pattern.factory.FactoryForStrategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * @author huangqingshi * @Date 2019-01-31 */ @Controller public class StrategyController { @Autowired FactoryForStrategy factoryForStrategy; @PostMapping("/strategy") @ResponseBody public String strategy(@RequestParam("key") String key) { String result; try { result = factoryForStrategy.getStrategy(key).doOperation(); } catch (Exception e) { result = e.getMessage(); } return result; } }
打开swagger
进行测试,输入one
,返回one
。输入four
,返回no strategy defined
。后续如果有新策略的话,直接实现即可。
分类:
Spring Cloud
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)