餓漢式(線程不安全):
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
懶漢式:
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
大家或許已經(jīng)注意到<code>synchronized</code>關鍵字亏推,這使得在多線程的情況下保證單例對象的唯一性。這種方式在一定程度上節(jié)約了資源束亏,但是第一次加載時需要及時進行實例化故响,反應稍慢儿咱,而且每次調(diào)用<code>getInstance()</code>都會進行同步,造成不必要的同步開銷性置,不建議使用拾并。
DCL方式實現(xiàn)單例(推薦)
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
DCL方式既實現(xiàn)了需要才初始化單例,又保證了線程安全鹏浅,且<code>getInstance</code>調(diào)用時不立即進行同步鎖嗅义,避免了不必要的開銷。
單例在使用時需要注意:
單例對象如果持有<code>Context</code>,能容易造成內(nèi)存泄漏隐砸,所以在傳給單例對象的<code>Context</code>最好是<code>Application Context</code>