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


}
相关推荐
CoderYanger18 小时前
贪心算法:4.摆动序列
java·算法·leetcode·贪心算法·1024程序员节
默 语18 小时前
Spring-AI vs LangChain4J:Java生态的AI框架选型指南
java·人工智能·spring·ai·langchain·langchain4j·spring-ai
古城小栈19 小时前
Spring Boot 集成区块链:智能合约调用接口开发全解析
spring boot·区块链·智能合约
kk哥889919 小时前
springboot静态资源的核心映射规则
java·spring boot·后端
老毛肚19 小时前
Java两种代理模式详解
java·开发语言·代理模式
要站在顶端19 小时前
Jenkins PR编号提取&环境变量赋值问题总结
java·servlet·jenkins
愚公移码19 小时前
蓝凌EKP产品:Hibernate 中 SessionFactory、Session 与事务的关系
java·数据库·hibernate·蓝凌
TT哇19 小时前
【每日八股】面经常考
java·面试
何中应19 小时前
【面试题-4】JVM
java·jvm·后端·面试题
老毛肚19 小时前
黑马头条-再回首
java