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