当前位置: 首页 > news >正文

JAVA策略模式demo【设计模式系列】

策略模式用在统一的入口,但需要根据某个类型判断后续执行逻辑,例如我最近遇到的场景:我需要对接一个设备,前端请求我这边,我再去和设备交互,但设备种类很多,各自有自己的接入规则!传统代码会变成if{}else{}面条代码,而且扩展性不佳,如果后续新增了设备,需要去修改这里的代码,非常不优雅~
闲话少说上代码!

1.创建一个枚举,包含所有策略

public enum StrategyEnums {STRATEGY_ONE("strategyOne", "策略1"),STRATEGY_TWO("strategyTwo", "策略2"),STRATEGY_THREE("strategyThree", "策略3");private String code;private String name;StrategyEnums(String code, String name) {this.code = code;this.name = name;}
}

2.创建一个接口,含执行方法

public interface StrategyService {void run();
}

3.创建3个策略的业务类,实现【StrategyService】接口

public class StrategyServiceImpl1 implements StrategyService{@Overridepublic void run() {System.out.println("运行策略1的业务代码");}
}

4.创建工厂类,用于初始化各策略,提供获取策略的静态方法

public class StrategyFactory {static final Map<StrategyEnums, StrategyService> map = new HashMap<>();static {map.put(StrategyEnums.STRATEGY_ONE, new StrategyServiceImpl1());map.put(StrategyEnums.STRATEGY_TWO, new StrategyServiceImpl2());map.put(StrategyEnums.STRATEGY_THREE, new StrategyServiceImpl3());}public static StrategyService getStrategy(StrategyEnums strategyEnums) {return map.get(strategyEnums);}
}

5.创建控制器,对前端提供接口【可选】

@RestController("design")
public class DesignController {@GetMapping("strategy")public void strategyTest(StrategyEnums strategyEnums) {StrategyService strategy = StrategyFactory.getStrategy(strategyEnums);strategy.run();}
}

6.创建测试类,调用接口【可选】

@SpringBootTest
public class DesignTest {@AutowiredDesignController designController;/*** 策略模式测试*/@Testpublic void strategyTest() {designController.strategyTest(StrategyEnums.STRATEGY_ONE);designController.strategyTest(StrategyEnums.STRATEGY_TWO);designController.strategyTest(StrategyEnums.STRATEGY_THREE);}
}

为了方便演示,我是从测试方法里调用的接口,实际上可以用postman走接口执行,或在测试类里使用工厂直接调用。下面查看执行结果:
在这里插入图片描述
假设后续新增一个需要对接的设备,我只需要在枚举增加一个类型,在工厂里初始化,然后创建一个新的策略,完成业务代码即可,优雅!实在是优雅~
在这里插入图片描述

http://www.dtcms.com/a/270961.html

相关文章:

  • 自动化Trae Apollo参数解释的批量获取
  • 苍穹外卖项目日记(day04)
  • ASP.NET Core 8 轻松配置Serilog日志
  • 智慧码头船舶网络部署5G工业路由器无人值守场景应用
  • 无人设备遥控器之双向通讯技术篇
  • 【机器人】Aether 多任务世界模型 | 4D动态重建 | 视频预测 | 视觉规划
  • C++并发编程-11. C++ 原子操作和内存模型
  • Linux驱动学习day20(pinctrl子系统驱动大全)
  • Ubuntu防火墙缺失问题(unit firewalld.service could not be found, ubuntu 22)
  • EFK9.0.3 windows搭建
  • Linux系统管理实战:生成大文件与定位磁盘挂载点
  • 专题:2025母婴行业洞察报告|附60+份报告PDF汇总下载
  • Linux中shell(外壳)和内核(kernel)的关系
  • Claude Code:终端上的 AI 编码助手,潜力与挑战并存
  • 从零用java实现 小红书 springboot vue uniapp(13)模仿抖音视频切换
  • 华为数通HCIA vs HCIP:新手入门选哪个更合适?
  • 利用sCMOS科学相机测量激光散射强度
  • Rk3568驱动开发_阻塞IO_15
  • SQL Server通过存储过程实现飞书消息卡片推送
  • Live555-RTSP服务器
  • nl2sql的解药pipe syntax
  • 【工具变量】上市公司企业金融强监管数据、资管新规数据(2001-2024年)
  • 【YOLOv11-目标检测】目标检测数据格式(官方说明)
  • S7-200 SMART :通过以太网下载程序详细步骤
  • React、Vue、Angular的性能优化与源码解析概述
  • Qt6中模态与非模态对话框区别
  • 供应链管理-采购:谈判方式、理念、技巧
  • DolphinScheduler 3.2.0 Worker启动核心源码解析
  • 一天一道Sql题(day05)
  • IntelliJ IDEA 2025.1.3创建不了java8的项目