我想使用以下模式在java中创建一个单例
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
但是当我要调用的私有构造函数是
private Singleton(Object stuff) {... }
我如何传递stuff
给INSTANCE = new Singleton()
? 如在INSTANCE = new Singleton(stuff);
重写上面的代码片段:
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton(Object stuff) { ... }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(Object stuff) {
return SingletonHolder.INSTANCE;//where is my stuff passed in?
}
}
编辑:
对于那些声称这种模式不是线程安全的人,请在此处阅读:http ://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh 。
我传入的对象是 android 应用程序上下文。