首页 > 其他 > 详细

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

时间:2020-07-14 10:25:58      阅读:51      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!