且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建单例类

更新时间:2023-11-13 15:34:22

根据对您问题的评论:

我有一个包含一些键值对的属性文件,这是整个应用程序都需要的,这就是我考虑单例类的原因.此类将从文件中加载属性并保留它,您可以在应用程序的任何位置使用它

不要使用单例.您显然不需要一次性 lazy 初始化(这就是单例的全部意义所在).您需要一次性直接初始化.只需将其设为静态并将其加载到静态初始化程序中即可.

Don't use a singleton. You apparently don't need one-time lazy initialization (that's where a singleton is all about). You want one-time direct initialization. Just make it static and load it in a static initializer.

例如

public class Config {

    private static final Properties PROPERTIES = new Properties();

    static {
        try {
            PROPERTIES.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
        } catch (IOException e) {
            throw new ExceptionInInitializerError("Loading config file failed.", e);
        }
    }

    public static String getProperty(String key) {
        return PROPERTIES.getProperty(key);
    }

    // ...
}