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


}
相关推荐
毕设源码-朱学姐12 分钟前
【开题答辩全过程】以 日程管理系统为例,包含答辩的问题和答案
java
a努力。16 分钟前
京东Java面试被问:双亲委派模型被破坏的场景和原理
java·开发语言·后端·python·面试·linq
小毛驴85022 分钟前
Maven同时配置阿里云仓库和私有仓库
java·阿里云·maven
刘975323 分钟前
【第25天】25c#今日小结
java·开发语言·c#
不如打代码KK25 分钟前
Springboot如何解决跨域问题?
java·spring boot·后端
豆沙沙包?27 分钟前
2026年--Lc330-394. 字符串解码(栈)--java版
java·开发语言
蓝程序28 分钟前
Spring AI学习 程序接入大模型
java·人工智能·spring
nice_lcj52029 分钟前
数据结构之树与二叉树:重点梳理与拓展
java·数据结构
毕设源码-钟学长29 分钟前
【开题答辩全过程】以 助学贷款管理系统为例,包含答辩的问题和答案
java
亓才孓31 分钟前
任意大小的整数和任意精度的小数的API方法
java