確保某個(gè)類有且只有一個(gè)對(duì)象莱预,避免產(chǎn)生多個(gè)對(duì)象消耗過(guò)多的資源能曾,或者某種類型的對(duì)象只應(yīng)該有且只有一個(gè)。
例如:創(chuàng)建一個(gè)對(duì)象需要消耗的資源過(guò)多实蔽,如要訪問(wèn)IO和數(shù)據(jù)庫(kù)等資源,這時(shí)就要考慮使用單例谨读。
單例關(guān)鍵點(diǎn):
構(gòu)造方法私有化
靜態(tài)方法或者枚舉返回單例類對(duì)象
多線程環(huán)境下確保類對(duì)象只有一個(gè)
類對(duì)象在反序列化時(shí)不會(huì)重新構(gòu)建對(duì)象
實(shí)現(xiàn)方法:
1.餓漢式
public class Singleton {
private static final Singleton mInstance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return mInstance;
}
}
2.懶漢式
synchronized關(guān)鍵字盐须,同步鎖,保證多線程情況下單例
public class Singleton {
private static Singleton mInstance = null;
private Singleten() {}
public static synchronized Singleton getInstance() {
if (mInstance == null) {
mInstance = new Singleton();
}
return mInstance;
}
}
3.雙重檢查鎖 DCL
DCL能在需要時(shí)實(shí)例化對(duì)象漆腌,又能保證線程安全,且初始化實(shí)例后不再進(jìn)入同步代碼塊
volatile阶冈,它的意思是:被volatile修飾的變量的值闷尿,將不會(huì)被本地線程緩存,所有對(duì)該變量的讀寫都是直接操作共享內(nèi)存女坑,從而確保多個(gè)線程能正確的處理該變量填具。
public class Singleton {
private volatile static Singleton mInstance = null;
private Singleton() {}
public static Singleton getInstance() {
if (mInstance == null) {
synchronized (Singleton.class) {
if (mInstance == null) {
mInstance = new Singleton();
}
}
}
return mInstance;
}
}
4.靜態(tài)內(nèi)部類
public class Singleton {
private Singleton() {}
public static Singleton getInstance() {
return SingletonHolder.mInstance;
}
private static class SingletonHolder {
private static final Singleton mInstance = new Singleton();
}
}
5.枚舉
public enum SingletonEnum {
INSTANCE;
public void doSomething() {
............
}
}
Android中的應(yīng)用:
系統(tǒng)級(jí)別的服務(wù),LayoutInflater等
優(yōu)點(diǎn):
減小內(nèi)存開(kāi)支匆骗,防止資源多重占用