1. 程式人生 > 實用技巧 >工廠模式+反射的簡單應用

工廠模式+反射的簡單應用

專案中採用工廠模式加策略模式,但是程式碼中還是存在大量的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;
        }
    }