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

java实现策略模式

创建策略接口

public interface Calculate {public int operation(int a, int b);}

实现接口

加法策略

@Component
public class AddCalculate implements Calculate {@Overridepublic int operation(int a, int b) {return a + a;}
}

减法策略

@Component
public class SubCalculate implements Calculate {@Overridepublic int operation(int a, int b) {return a - a;}
}

策略实现类

在springboot中,对于添加了 @Autowired 的map会自动将实现类注入到map中,key是beanid,value是注入的对象实例

@Component
public class CalculateFactory {@Autowiredprivate Map<String, Calculate> calculateMap;public int calculate(String calculate, int a, int b) throws Exception {return Optional.ofNullable(calculateMap.get(calculate)).orElseThrow(() -> new RuntimeException("异常")).operation(a, b);}}

使用

@RestController
@RequestMapping("/demo")
public class DemoController {@Autowiredprivate CalculateFactory calculateFactory;@GetMapping("/calculate")public int calculate() throws Exception {return calculateFactory.calculate("addCalculate", 1, 1);}}


http://www.mrgr.cn/news/24563.html

相关文章:

  • 路径规划 C++(Ⅱ)
  • 记录word转xml文件踩坑
  • 测测万用表?合宙功耗分析仪Air9000Air9000P齐出动
  • Plotly 画交互式3D图
  • 软件测试常用的7种方法,最后一个是升职加薪关键!(零基础小白转行IT互联网高效进阶)
  • 一文读懂DNS污染
  • Threejs之光线投射Raycaster交互
  • Vue 2 中的 `$set` 方法详解
  • SOME/IP通信协议在汽车业务具体示例
  • LeetCode - 17 电话号码的字母组合
  • 828华为云征文 | Flexus X实例与Harbor私有镜像仓库的完美结合
  • vscode中前端项目文件格式化备份
  • 老旧电力系统安全隐患增加 该如何预防电气线路老化等因素引发的电气火灾呢?
  • SpringBoot基础 -- 框架介绍
  • 云电脑玩《黑神话:悟空》游戏到底咋样?说说心里话…
  • 从大脑图谱/ROI中提取BOLD信号
  • 【C++ Primer Plus习题】14.5
  • 【最新综述】基于深度学习的超声自动无损检测(下)
  • 使用 modelscope产生的问题和解决方案
  • java 中线程的等待和唤醒