1. /**
    2. * 面向接口编程
    3. */
    4. public interface IService {
    5. void handle();
    6. String putType();
    7. }
    1. /**
    2. * 枚举
    3. */
    4. public enum TypeEnum {
    5. //
    6. a, b, c, d, e;
    7. }
    1. /**
    2. * A实现类
    3. */
    4. @Service
    5. public class AServiceImpl implements IService {
    6. @Override
    7. public void handle() {
    8. System.out.println("A测试");
    9. }
    10. @Override
    11. public String putType() {
    12. return TypeEnum.a.name();
    13. }
    14. }
    1. /**
    2. * B实现类
    3. */
    4. @Service
    5. public class BServiceImpl implements IService {
    6. @Override
    7. public void handle() {
    8. System.out.println("B测试");
    9. }
    10. @Override
    11. public String putType() {
    12. return TypeEnum.b.name();
    13. }
    14. }
    1. /**
    2. * 工厂方法
    3. */
    4. @Service
    5. public class ServiceFactory {
    6. private final Map<String, IService> map = new ConcurrentHashMap<>();
    7. public ServiceFactory(List<IService> iServices) {
    8. iServices.forEach(s -> map.put(s.putType(), s));
    9. }
    10. public IService getService(String type) {
    11. if (null == type || type.isEmpty()) {
    12. System.out.println("类型为空");
    13. }
    14. return map.get(type);
    15. }
    16. }
    1. /**
    2. * 接口调用
    3. */
    4. @RestController
    5. public class FactoryRest {
    6. @Autowired
    7. private ServiceFactory serviceFactory;
    8. @RequestMapping("/test")
    9. public void test(String type) {
    10. IService service = serviceFactory.getService(type);
    11. if (null == service) {
    12. System.out.println("接口为空!");
    13. }
    14. service.handle();
    15. }
    16. }