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


}
相关推荐
Lin_Aries_04214 分钟前
基于 CI/CD(Jenkins)将 Spring Boot 应用自动部署到 Kubernetes 集群
spring boot·ci/cd·docker·容器·自动化·jenkins
咖啡Beans7 分钟前
SseEmitter + WebClient + Flux实现SSE事件流推送
java·spring boot·flux
你三大爷19 分钟前
Safepoint的秘密探寻
java·后端
努力也学不会java42 分钟前
【Java并发】揭秘Lock体系 -- condition等待通知机制
java·开发语言·人工智能·机器学习·juc·condition
我需要打球1 小时前
SpringMVC的执行流程
java·servlet
醉、倾城1 小时前
面向开发人员的macOS入门教程
macos·策略模式
瑞士卷@1 小时前
JDBC进阶之连接池的配置(Druid与HikariCP)
java·开发语言·数据库
xiaopengbc2 小时前
泛型在Java集合框架中的应用有哪些?
java·开发语言·python
沐浴露z2 小时前
一篇文章入门RabbitMQ:基本概念与Java使用
java·分布式·rabbitmq
失散132 小时前
分布式专题——24 Kafka功能扩展
java·分布式·云原生·架构·kafka