Java 在单例类中读取大型xml文件的最佳方法是什么

Java 在单例类中读取大型xml文件的最佳方法是什么,java,design-patterns,constructor,singleton,Java,Design Patterns,Constructor,Singleton,我有一个singleton类,它从包含大量元素的xml文件中读取一些属性。目前,我正在singleton类的构造函数中读取xml文件。一旦xml中的条目被读取,我就可以从singleton实例访问这些条目,而无需反复读取xml。我想知道这是一个正确的方法,还是有比这更好的方法来完成它 如果您想延迟加载属性,那么您可以按如下方式编写该类,它也可以在多线程环境中工作 class Singleton { private static Singleton instance; privat

我有一个singleton类,它从包含大量元素的xml文件中读取一些属性。目前,我正在singleton类的构造函数中读取xml文件。一旦xml中的条目被读取,我就可以从singleton实例访问这些条目,而无需反复读取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)
        }
    }
}

只要在singleton实例返回到调用代码之前读取XML,那么具体在哪里执行(构造函数、静态初始值设定项、私有init方法)并不重要。