- 编写策略接口类
public interface DemoService { void doQuery(); }
- 编写策略实现类
@Service("test1") @Slf4j public class Test1ServiceImpl implements DemoService { @Override public void doQuery() { // do something } }
@Service("test2") @Slf4j public class Test2ServiceImpl implements DemoService { @Override public void doQuery() { // do something } }
- 构建策略工厂, Service自动注入
@Component public class DemoStrategyFactory { @Autowired Map<String, DemoService> DemoServices = new ConcurrentHashMap<>(); public DemoService getDemoService(String component){ DemoService demoService = DemoServices.get(component); if(demoService== null) { throw new RuntimeException("策略模式没找到对应实现类"); } return demoService; } }
- Controller中直接使用
@Autowired private DemoStrategyFactory demoStrategyFactory; @PostMapping("/test") public void test(@Valid @RequestParam String functionId){ // eg: functionId = "test2" DemoService demoService = demoStrategyFactory.getDemoService(functionId); demoService.doQuery(); }