Aru*_*hny 31 java singleton design-patterns
在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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是在以下测试用例中实现失败了
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
怎么解决这个?
谢谢
Bal*_*usC 18
根据你的问题评论:
我有一个包含一些键值对的属性文件,这在整个应用程序中是需要的,这就是我考虑单例类的原因.此类将从文件加载属性并保留它,您可以从应用程序的任何位置使用它
不要使用单身人士.你显然不需要一次性的懒惰初始化(这就是单身人士所在的地方).您想要一次性直接初始化.只需将其设置为静态并将其加载到静态初始化程序中即可.
例如
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);
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47842 次 |
| 最近记录: |