【发布时间】:2011-05-20 18:14:14
【问题描述】:
在 java 中创建单例类的最佳/正确方法是什么?
我发现的一个实现是使用私有构造函数和 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");
}
}
}
如何解决?
谢谢
【问题讨论】:
-
根据我多年的专业经验,在 99.99% 的情况下,最好的方法是不这样做。你认为你需要一个 Singleton 来做什么,真的?
-
首先,单身人士是邪恶的。其次,单例是全局变量,第三,不要使用单例。此外,你不能阻止反思能够对你的班级造成坏事。不要尝试!
-
我想我会听取你的建议,如果有人使用反射来搞砸……这是他们的问题……不是我的问题。
-
@Arun,我会创建一次对象并将其传递给所有需要设置的对象的构造函数。
-
伙计们,提出的问题是解决问题,而不是去 Dr. House 询问单人是好是坏。
标签: java design-patterns singleton