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

Spring boot 策略模式

public abstract class Node {/*** 执行** @param a* @param b* @return*/public abstract Integer execute(int a, int b);
}
package my.node;import org.springframework.stereotype.Component;@Component("exec")
public class ExecNode extends Node {@Overridepublic Integer execute(int a, int b) {return a + b;}
}
package my.node;import org.springframework.stereotype.Component;@Component("todo")
public class TodoNode extends Node {@Overridepublic Integer execute(int a, int b) {return a + b;}
}

工厂

package my;import my.node.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.util.Map;
import java.util.Optional;@Component
public class NodeFactory {/*** Spring会自动将Strategy接口的实现类注入到这个Map中,key为bean id,value值则为对应的策略实现类*/@Autowiredprivate Map<String, Node> nodeMap;/*** 获取相应的节点** @param nodeName* @return*/public Node getNode(String nodeName) {Node targetNode = Optional.ofNullable(nodeMap.get(nodeName)).orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));return targetNode;}
}

使用

package my;import my.node.Node;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
@WebAppConfiguration
public class CommandFactoryTest {@Autowiredprivate NodeFactory nodeFactory;@Testpublic void execute() throws Exception {Node node = nodeFactory.getNode("exec");}}

http://www.xdnf.cn/news/9393.html

相关文章:

  • YOLOv5 详解:从原理到实战的全方位解析
  • 35. 自动化测试开发之使用oracle连接池实现oracle数据库操作
  • 34. 自动化测试开发之使用mysql异步连接池实现mysql数据库操作
  • 碰一碰系统源码搭建
  • DH加密详解
  • 什么是PLM系统?PLM主要功能有哪些?2025主流PLM系统介绍
  • 第五十五节:综合项目实践-实时人脸美化滤镜
  • 三轴云台之积分分离PID控制算法篇
  • 【通关文件操作(上)】--文件的意义和概念,二进制文件和文本文件,文件的打开和关闭,文件的顺序读写
  • 鸿蒙运动开发实战:打造 Keep 式轨迹播放效果
  • Java Stream API 终止操作的详细解析
  • QML之Canvas
  • 数组名的大小理解
  • <b> 与 <span> 等行内元素添加 margin-top 或 margin-bottom 不生效问题
  • CarPropertyService 介绍
  • 【FAQ】spring boot 3 集成 nacos
  • pgsql 查看每张表大小
  • 创建vue项目
  • 3D Web轻量化引擎HOOPS Communicator实时协作功能深度解析
  • 小黑黑大模型应用日常摸索中:初次使用langchain智能体调用工具,准备继续深入
  • 题解——相交链表(力扣160 easy)
  • Java研学-MybatisPlus(三)
  • 磁盘管理练习题
  • 《Python基础》第1期:人生苦短,我用Python
  • Java基础 5.27
  • Oracle初识
  • 遗传算法简明指南:思路解析与C++实现
  • C++优先队列(priority_queue)使用详解
  • 计算机系统结构-第四章节-背诵
  • 使用Auto-Coder对js文件进行审计并修复漏洞1.3 1.4 1.5版本