项目中采用工厂模式加策略模式,但是代码中还是存在大量的if esle 或者switch,为了消除冗余的代码,采用工厂+反射解决.
@Autowired private ApplicationContext context; public RecoveryInterface getInterface(Product product) { RecoveryInterface recoveryInterface; try { String clazzStr = "具体实现类的相对路径,要加上**.**" + product.getProductInterface(); Class<?> aClass = Class.forName(clazzStr); //刚开始采用这样的反射后来发现 发射生成的类没有加入ico容器中,自然无法获取到容器内容,改进代码 //recoveryInterface = (RecoveryInterface) aClass.newInstance(); Object bean = context.getAutowireCapableBeanFactory() .createBean(aClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); recoveryInterface = (RecoveryInterface) bean; logger.info("factory:"+product.getProductInterface()); return recoveryInterface; } catch (Exception e) { e.printStackTrace(); return null; } }
原文:https://www.cnblogs.com/song1024/p/13297295.html