Spring boot 策略模式
public abstract class Node {/*** 执行** @param a* @param b* @return*/public abstract Integer execute(int a, int b);
}
package my.node;import org.springframework.stereotype.Component;@Component("exec")
public class ExecNode extends Node {@Overridepublic Integer execute(int a, int b) {return a + b;}
}
package my.node;import org.springframework.stereotype.Component;@Component("todo")
public class TodoNode extends Node {@Overridepublic Integer execute(int a, int b) {return a + b;}
}
工厂
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值则为对应的策略实现类*/@Autowiredprivate 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;}
}
使用
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 {@Autowiredprivate NodeFactory nodeFactory;@Testpublic void execute() throws Exception {Node node = nodeFactory.getNode("exec");}}