工厂模式+反射的简单应用

项目中采用工厂模式加策略模式,但是代码中还是存在大量的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;
        }
    }

  

posted @ 2020-07-14 09:28  i小松i  阅读(197)  评论(0)    收藏  举报