Spring boot 策略模式

java 复制代码
public abstract class Node {


    /**
     * 执行
     *
     * @param a
     * @param b
     * @return
     */
    public abstract Integer execute(int a, int b);
}
java 复制代码
package my.node;

import org.springframework.stereotype.Component;


@Component("exec")
public class ExecNode extends Node {
    @Override
    public Integer execute(int a, int b) {
        return a + b;
    }
}
java 复制代码
package my.node;

import org.springframework.stereotype.Component;


@Component("todo")
public class TodoNode extends Node {
    @Override
    public Integer execute(int a, int b) {
        return a + b;
    }
}

工厂

java 复制代码
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值则为对应的策略实现类
     */
    @Autowired
    private 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;
    }
}

使用

java 复制代码
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 {
    @Autowired
    private NodeFactory nodeFactory;

    @Test
    public void execute() throws Exception {

        Node node = nodeFactory.getNode("exec");
    }


}
相关推荐
古法老登瞎折腾5 小时前
大数据智能运维实战(十一):运维 MCP 的工程化——权限、限流、审计与错误处理
java·大数据·运维·spring ai·mcp
智能运维指南6 小时前
研制过程“两张皮“怎么破:研制一体化支撑平台的定位、能力边界与落地前提
java·前端·人工智能·嘉为蓝鲸
yz_aiks7 小时前
Spring AI 2.1 ChatMemory 已过时用什么替代:迁移到 Session Memory 实战(JDBC 存储与会话压缩)
java·spring boot·大模型·ai agent·spring ai
金銀銅鐵7 小时前
[Java] 用 GUI 展示 EnumMap 增删键值对时的内部变化
java·后端·ai编程
学长毕设7 小时前
基于SpringBoot的上门洗车服务系统设计与实现
java·spring boot·后端
jason成都7 小时前
RTKLIB-Java 多基线联合RTK:FIX率从0%到91.5%的三层根因修复
java·gnss·rtklib·rtklib_java
鱼宵8 小时前
Stream 终端操作一次讲透:collect、count、reduce 怎么选
java·stream·终端操作
白山编程大哥8 小时前
Java 后端如何优雅地把 List 集合返回给前端
java·前端·list
Linux运维技术栈8 小时前
CVE-2026-91403 高危漏洞修复:Rocky Linux 9 多版本 JDK 环境清理实操
java·linux·运维
On The Road :8 小时前
Java 多线程详解:从入门到线程安全
java·python·安全