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");
    }


}
相关推荐
liangshanbo12156 小时前
主系统登录后,子系统怎么实现自动登录?
java·网络·数据库
ShineWinsu6 小时前
对于Redis:缓存的解析
java·redis·缓存·缓存穿透·缓存击穿·缓存雪崩·缓存预热
rannn_1117 小时前
【Java面试题】高频面试题1|Java 后端、MySQL、Redis 与 RAG 面试整理
java·jvm·数据库·后端·面试
写后端的胖头鱼7 小时前
一文详解Spring 事务失效场景
java·spring·事务·transactional·事务传播机制
Q26433650237 小时前
【有源码】基于Spring Boot和Vue的在线考试与交流系统-教育信息化背景下在线考试与交流一体化平台
java·vue.js·spring boot·mysql·spring·毕业设计·课程设计
Mikko77 小时前
JVM 线上排查实战(七):jps 看不到进程、jstack 报不允许的操作怎么办?attach 失败的六种情况实测
java·运维·jvm·后端
jianjinwssy7 小时前
MyBatis-Plus 从入门到实战:常用功能与核心原理
java·mybatis
会编程的吕洞宾7 小时前
Spring AI 2.0 会话记忆实战,让 AI 助手记住每一次对话
java·人工智能·spring
小宋10217 小时前
Agent 工具升级如何不破坏线上:Tool Schema 版本兼容与契约测试
java·人工智能·后端·spring
汤米粥7 小时前
后端开发主流技术方案
java·python·golang·php·nodejs·后端开发