次のパターンを使用して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 アプリケーション コンテキストです。