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