创建策略接口
java
public interface Calculate {
public int operation(int a, int b);
}
实现接口
加法策略
java
@Component
public class AddCalculate implements Calculate {
@Override
public int operation(int a, int b) {
return a + a;
}
}
减法策略
java
@Component
public class SubCalculate implements Calculate {
@Override
public int operation(int a, int b) {
return a - a;
}
}
策略实现类
在springboot中,对于添加了 @Autowired的map会自动将实现类注入到map中,key是beanid,value是注入的对象实例
java
@Component
public class CalculateFactory {
@Autowired
private Map<String, Calculate> calculateMap;
public int calculate(String calculate, int a, int b) throws Exception {
return Optional.ofNullable(calculateMap.get(calculate))
.orElseThrow(() -> new RuntimeException("异常")).operation(a, b);
}
}
使用
java
@RestController
@RequestMapping("/demo")
public class DemoController {
@Autowired
private CalculateFactory calculateFactory;
@GetMapping("/calculate")
public int calculate() throws Exception {
return calculateFactory.calculate("addCalculate", 1, 1);
}
}