創建Java單身我想用以下方式使用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應用程序上下文。
你爲什麼認爲你的應用程序需要一個singleton? –
您的描述可能是您不應該使用單身人士的標誌。特別是,如果你調用:Singleton.getInstance(object1); Singleton.getInstance(Object2的);'???你現在有兩個單例嗎?你是否改變了第一個例子?等等。 – assylias
@LuiggiMendoza如果你想讓一個點使它。我不打算寫一篇關於爲什麼我需要一個單身人士的論文。 –