-1
我有一个单元类,它从具有相当数量的元素的xml文件读取一些属性。目前,我正在读取XML文件单例类的构造函数。一旦读取了xml中的条目,我就可以从单例实例访问这些条目,而无需一次又一次读取xml。我想知道这是否是一种正确的方法,还是有更好的方法来完成它。什么是读取单个类中的大型XML文件的最佳方式
我有一个单元类,它从具有相当数量的元素的xml文件读取一些属性。目前,我正在读取XML文件单例类的构造函数。一旦读取了xml中的条目,我就可以从单例实例访问这些条目,而无需一次又一次读取xml。我想知道这是否是一种正确的方法,还是有更好的方法来完成它。什么是读取单个类中的大型XML文件的最佳方式
如果你想懒惰地加载属性,那么你可以写下如下的类,它也可以在多线程环境中工作。
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)
}
}
}
只要你的XML在单例实例返回到调用代码之前被读取,你在什么地方这样做(构造函数,静态初始化方法,私有init方法)并不重要。 – Thilo