策略模式是开发中常用的一种设计模式,主要解决在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护的问题。看了网上很多关于策略模式的上下文切换类实现都不甚优雅,故而想总结分享一篇自我感觉比较优雅的处理方式,方便大家一起学习。
该方式是比较常用的,相对比较优雅,能满足动态获取不同实现类的功能。废话不多说直接上代码。
策略类:
public interface Strategy { /** * 策略方法 */ void method();}
策略实现类:
@Service(value = "strategyA")public class StrategyA implements Strategy { /** * 策略方法 */ @Override public void method() { System.out.println("我是A策略实现方案!"); }} @Service(value = "strategyB")public class StrategyB implements Strategy { /** * 策略方法 */ @Override public void method() { System.out.println("我是B策略实现方案!"); } @Service(value = "strategyC")public class StrategyC implements Strategy { /** * 策略方法 */ @Override public void method() { System.out.println("我是C策略实现方案!"); }}
枚举类:
public enum StrategyEnum { /** * 策略枚举类 */ STRATEGY_A(1, "strategyA"), STRATEGY_B(2, "strategyB"), STRATEGY_C(3, "strategyC"); private Integer code; private String name; StrategyEnum(Integer code, String name) { this.code = code; this.name = name; } public static StrategyEnum getByCode(Integer code) { StrategyEnum[] values = StrategyEnum.values(); for (StrategyEnum strategyEnum : values) { if (strategyEnum.getCode().equals(code)) { return strategyEnum; } } return null; } /** * Getter method for property <tt>code</tt>. * * @return property value of code */ public Integer getCode() { return code; } /** * Getter method for property <tt>name</tt>. * * @return property value of name */ public String getName() { return name; }}
上下文切换类:
@Componentpublic class StrategyContext { private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>(); @Autowired private ApplicationContext applicationContext; @PostConstruct private void init() { strategyMap.putAll(applicationContext.getBeansOfType(Strategy.class)); } public Strategy getInstance(Integer code) { String beanName = StrategyEnum.getByCode(code).getName(); return this.getInstanceByBeanName(beanName); } private Strategy getInstanceByBeanName(String beanName) { if (!StringUtils.isEmpty(beanName)) { return strategyMap.get(beanName); } return null; } }
测试:
@RestControllerpublic class StrategyController { @Autowired private StrategyContext context; @RequestMapping("/method") public String method() { return context.getInstance(code).method(); }
测试结果:
原因是:@Autowired 注释中提到In case of a java.util.Collection or java.util.Map dependency type, the container will autowire all beans matching the declared value type. In case of a Map, the keys must be declared as type String and will be resolved to the corresponding bean names.
意思是:以java.util.Collection 或java.util.Map 为例。映射依赖项类型,容器将自动连接所有与声明值类型匹配的bean。对于映射,键必须声明为类型String,并将解析为相应的bean名称。
具体实现如下:
@Componentpublic class StrategyContext { private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>(); @Autowired public StrategyContext(Map<String, Strategy> strategyMap) { this.strategyMap.clear(); strategyMap.forEach((k, v) -> this.strategyMap.put(k, v)); } public Strategy getInstance(Integer code) { String beanName = StrategyEnum.getByCode(code).getName(); return this.getInstanceByBeanName(beanName); } private Strategy getInstanceByBeanName(String beanName) { if (!StringUtils.isEmpty(beanName)) { return strategyMap.get(beanName); } return null; }}
测试结果同方式一,这里就不演示了。
这是交给spring上下文容器去管理,我们自己不需要再做实现了。实现方式如下:
@Componentpublic class StrategyContext { @Autowired private ApplicationContext applicationContext; public Strategy getInstance(Integer code) { String beanName = StrategyEnum.getByCode(code).getName(); return this.getInstanceByBeanName(beanName); } private Strategy getInstanceByBeanName(String beanName) { if (!StringUtils.isEmpty(beanName)) { return (Strategy) applicationContext.getBean(beanName); } return null; } }
其实这种方式和第二种差不多,第二种也是借助spring,但是不同点是未进行缓存,从beanFactory中获取。测试结果同方式一,这里不再演示了。
这三种动态获取策略实现类的方法,个人觉得大同小异,都是通过实现类beanName实现动态的效果,其实还有一种比较简单的方式就是通过注解@Qualifier(value = "strategyA")+@Autowired private Strategy strategy;来决定调用哪个实现类,这种适用于某一种场景的调用,无需聚合所有调用场景,如果想动态实现,推荐上面三种。策略模式的枚举类也可以用注解的方式实现,这里有兴趣的同学可以自己尝试一下。另外有其他更好的实现方式也可以在下方留言,大家一起学习。
原网址: 访问
创建于: 2021-03-11 18:50:10
目录: default
标签: 无
未标明原创文章均为采集,版权归作者所有,转载无需和我联系,请注明原出处,南摩阿彌陀佛,知识,不只知道,要得到
java windows火焰图_mob64ca12ec8020的技术博客_51CTO博客 - 在windows下不可行,不知道作者是怎样搞的 监听SpringBoot 服务启动成功事件并打印信息_监听springboot启动完毕-CSDN博客 SpringBoot中就绪探针和存活探针_management.endpoint.health.probes.enabled-CSDN博客 u2u转换板 - 嘉立创EDA开源硬件平台 Spring Boot 项目的轻量级 HTTP 客户端 retrofit 框架,快来试试它!_Java精选-CSDN博客 手把手教你打造一套最牛的知识笔记管理系统! - 知乎 - 想法有重合-理论可参考 安宇雨 闲鱼 机械键盘 客制化 开贴记录 文本 linux 使用find命令查找包含某字符串的文件_beijihukk的博客-CSDN博客_find 查找字符串 ---- mac 也适用 安宇雨 打字音 记录集合 B站 bilibili 自行搭建 开坑 真正的客制化 安宇雨 黑苹果开坑 查找工具包maven pom 引用地 工具网站 Dantelis 介绍的玩轴入坑攻略 --- 关于轴的一些说法 --- 非官方 ---- 心得而已 --- 长期开坑更新 [本人问题][新开坑位]关于自动化测试的工具与平台应用 机械键盘 开团 网站记录 -- 能做一个收集的程序就好了 不过现在没时间 -- 信息大多是在群里发的 - 你要让垃圾佬 都去一个地方看难度也是很大的 精神支柱 [超级前台]sprinbboot maven superdesk-app 记录 [信息有用] [环境准备] [基本完成] [sebp/elk] 给已创建的Docker容器增加新的端口映射 - qq_30599553的博客 - CSDN博客 [正在研究] Elasticsearch, Logstash, Kibana (ELK) Docker image documentation elasticsearch centos 安装记录 及 启动手记 正式服务器 39 elasticsearch 问题合集 不断更新 6.1.1 | 6.5.1 两个版本 博客程序 - 测试 - bug记录 等等问题 laravel的启动过程解析 - lpfuture - 博客园 OAuth2 Server PHP 用 Laravel 搭建带 OAuth2 验证的 RESTful 服务 | Laravel China 社区 - 高品质的 Laravel 和 PHP 开发者社区 利用Laravel 搭建oauth2 API接口 附 Unauthenticated 解决办法 - 煮茶的博客 - SegmentFault 思否 使用 OAuth2-Server-php 搭建 OAuth2 Server - 午时的海 - 博客园 基于PHP构建OAuth 2.0 服务端 认证平台 - Endv - 博客园 Laravel 的 Artisan 命令行工具 Laravel 的文件系统和云存储功能集成 浅谈Chromium中的设计模式--终--Observer模式 浅谈Chromium中的设计模式--二--pre/post和Delegate模式 浅谈Chromium中的设计模式--一--Chromium中模块分层和进程模型 DeepMind 4 Hacking Yourself README.md update 20211011
Laravel China 简书 知乎 博客园 CSDN博客 开源中国 Go Further Ryan是菜鸟 | LNMP技术栈笔记 云栖社区-阿里云 Netflix技术博客 Techie Delight Linkedin技术博客 Dropbox技术博客 Facebook技术博客 淘宝中间件团队 美团技术博客 360技术博客 古巷博客 - 一个专注于分享的不正常博客 软件测试知识传播 - 测试窝 有赞技术团队 阮一峰 语雀 静觅丨崔庆才的个人博客 软件测试从业者综合能力提升 - isTester IBM Java 开发 使用开放 Java 生态系统开发现代应用程序 pengdai 一个强大的博主 HTML5资源教程 | 分享HTML5开发资源和开发教程 蘑菇博客 - 专注于技术分享的博客平台 个人博客-leapMie 流星007 CSDN博客 - 舍其小伙伴 稀土掘金 Go 技术论坛 | Golang / Go 语言中国知识社区
最新评论