How to create a singleton class

前端 未结 7 1051
粉色の甜心
粉色の甜心 2020-12-02 13:10

What is the best/correct way to create a singleton class in java?

One of the implementation I found is using a private constructor and a getInstance() method.

<
7条回答
  •  無奈伤痛
    2020-12-02 14:05

    As per the comment on your question:

    I've a properties file containing some keys value pairs, which is need across the application, that is why I was thinking about a singleton class. This class will load the properties from a file and keep it and you can use it from anywhere in the application

    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.

    E.g.

    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);
        }
    
        // ...
    }
    

提交回复
热议问题