2016-06-07 79 views
-1

我有一個單元類,它從具有相當數量的元素的xml文件讀取一些屬性。目前,我正在讀取XML文件單例類的構造函數。一旦讀取了xml中的條目,我就可以從單例實例訪問這些條目,而無需一次又一次讀取xml。我想知道這是否是一種正確的方法,還是有更好的方法來完成它。什麼是讀取單個類中的大型XML文件的最佳方式

+3

只要你的XML在單例實例返回到調用代碼之前被讀取,你在什麼地方這樣做(構造函數,靜態初始化方法,私有init方法)並不重要。 – Thilo

回答

1

如果你想懶惰地加載屬性,那麼你可以寫下如下的類,它也可以在多線程環境中工作。

class Singleton { 
    private static Singleton instance; 
    private Properties xmlProperties; 

    private Singleton() {} 

    public static Singleton getInstance() { 
     if(instance == null) { 
      synchronized(Singleton.class) { 
       if(instance == null) { 
        instance = new Singleton(); 
       } 
      } 
     } 
     return instance; 
    } 

    public Properties getXmlProperties() { 
     if(xmlProperties == null) { 
      initProperties(); 
     } 
     return xmlProperties; 
    } 

    private synchronized void initProperties() { 
     if(xmlProperties == null) { 
      //Initialize the properties from Xml properties file 
      // xmlProperties = (Properties from XML file) 
     } 
    } 
}