java - 如何创建单例类

标签 java design-patterns singleton

在 java 中创建单例类的最佳/正确方法是什么?

我发现的一个实现是使用私有(private)构造函数和 getInstance() 方法。

package singleton;

public class Singleton {

    private static Singleton me;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (me == null) {
            me = new Singleton();
        }

        return me;
    }
}

但是在下面的测试用例中实现是否失败

package singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {

    /**
     * @param args
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws IllegalArgumentException
     */
    public static void main(String[] args) throws SecurityException,
            NoSuchMethodException, IllegalArgumentException,
            InstantiationException, IllegalAccessException,
            InvocationTargetException {
        Singleton singleton1 = Singleton.getInstance();
        System.out.println(singleton1);

        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton2);

        Constructor<Singleton> c = Singleton.class
                .getDeclaredConstructor((Class<?>[]) null);
        c.setAccessible(true);
        System.out.println(c);

        Singleton singleton3 = c.newInstance((Object[]) null);
        System.out.println(singleton3);

        if(singleton1 == singleton2){
            System.out.println("Variable 1 and 2 referes same instance");
        }else{
            System.out.println("Variable 1 and 2 referes different instances");
        }
        if(singleton1 == singleton3){
            System.out.println("Variable 1 and 3 referes same instance");
        }else{
            System.out.println("Variable 1 and 3 referes different instances");
        }
    }

}

如何解决?

谢谢

最佳答案

根据您对问题的评论:

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

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

例如

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

    // ...
}

关于java - 如何创建单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4362911/

相关文章:

Cocoa TDD 和单例

java - (Android)如何捕获应用程序主线程终止(如果将其置于后台)

java - 无法在单台机器上运行的多个 jar 中共享单例实例

Javafx 项目不使用 Maven 编译

java - 在 Android 的 onSensorChanged() 中生成线程

java - 用于在 Java 学生关系表上支持不同过滤器集的设计模式

c++ - 重构 switch 语句的设计模式

java - HashMap使用对象实现一键多值

java - org.apache.axiom.om.util.AXIOMUtil 无法解析

java - 为什么我的 switch 语句中不能有重复的 case?