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


}
相关推荐
NE_STOP10 分钟前
MyBatis-mybatis入门与增删改查
java
孟陬3 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌3 小时前
一站式了解四种限流算法
java·后端·go
华仔啊4 小时前
Java 开发千万别给布尔变量加 is 前缀!很容易背锅
java
也些宝5 小时前
Java单例模式:饿汉、懒汉、DCL三种实现及最佳实践
java
Nyarlathotep01135 小时前
SpringBoot Starter的用法以及原理
java·spring boot
wuwen55 小时前
WebFlux + Lettuce Reactive 中 SkyWalking 链路上下文丢失的修复实践
java
SimonKing6 小时前
GitHub 10万星的OpenCode,正在悄悄改变我们的工作流
java·后端·程序员
Seven977 小时前
虚拟线程深度解析:轻量并发编程的未来趋势
java