单例的八种写法:推荐静态内部类和枚举

http://www.tuicool.com/articles/NVza2am

枚举类也是懒加载的(lazy loading)

举个栗子:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertiesUtil {
    
    private static class Inner {
        static{
            prop = fillProperty("/global.properties");
        }
        private static Properties prop;
    }

    private static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);

    public static Properties fillProperty(String propName) {
        InputStream in = null;
        try {
            in = PropertiesUtil.class.getResourceAsStream(propName);
            Properties prop = new Properties();
            prop.load(in);
            return prop;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != in)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }

    public static String getProperty(String key) {
        if (null != Inner.prop) {
            return Inner.prop.getProperty(key);
        }
        log.debug(" init prop failed.");
        return null;
    }

    public static String getProperty(String fileName, String key) {
        if (null != fileName && fileName.trim().length() != 0) {
            Properties prop = fillProperty(fileName);
            if (null != prop) {
                return prop.getProperty(key);
            }
            log.debug("can not find the file:" + fileName);
        }
        return null;
    }

}
原文地址:https://www.cnblogs.com/shoubianxingchen/p/5748645.html