一、定義
確保某一個(gè)類只有一個(gè)實(shí)例,而且自行實(shí)例化并鄉(xiāng)整個(gè)系統(tǒng)提供這個(gè)實(shí)例。
二、使用場(chǎng)景
確保某個(gè)類有且只有一個(gè)對(duì)象的場(chǎng)景,避免產(chǎn)生多個(gè)對(duì)象消耗多個(gè)資源?;蛘吣承╊愓加锰嗟馁Y源,不適合創(chuàng)建多個(gè)對(duì)象的情況;例如:數(shù)據(jù)庫(kù)、IO訪問,
android中使用單例模式的類:ImageLoader
三、單例的類圖

- 角色介紹
- Client 客戶端類
- Singleton 單例類
- 實(shí)現(xiàn)的關(guān)鍵點(diǎn)
- 構(gòu)造方法設(shè)置成為私有的private;
- 通過靜態(tài)方法或枚舉類型返回單例對(duì)象;
- 確保線程安全;
備注:?jiǎn)卫J降念?,有且只能有一個(gè)入口,注意盡量不要在單例模式中使用參數(shù),尤其是傳人類對(duì)象,會(huì)導(dǎo)致單例對(duì)象持有沒必要的引用,可能導(dǎo)致內(nèi)存泄漏。
四、代碼實(shí)例
1.餓漢模式
public class Person {
private static final Person instance = new Person();
private Person() {
}
public static Person getInstance() {
return instance;
}
}
最簡(jiǎn)單的單例模式,但是線程不安全。
2.懶漢模式
public class Person {
private static Person instance;
private Person() {}
public static synchronized Person getInstance() {
if (instance == null) {
instance = new Person();
}
return instance;
}
}
可以保證線程安全問題,但是每一次使用getInstance()方法都會(huì)進(jìn)行同步,而且第一次加載時(shí)需要進(jìn)行實(shí)例化,反應(yīng)稍慢;
3.Double Check Lock(DCL)實(shí)現(xiàn)單例模式
public class Person {
private static volatile Person instance;
private Person() {}
public static Person getInstance(){
if(instance == null){
synchronized (Person.class){
if(instance == null){
instance = new Person();
}
}
}
return instance;
}
}
第一次判空是為了避免不必要的重復(fù),
第二次判空是為了在null情況下創(chuàng)建實(shí)例;
通過倆次檢測(cè)初始化對(duì)象實(shí)例,優(yōu)點(diǎn)是僅在需要的時(shí)候會(huì)創(chuàng)建實(shí)例,資源利用率高,缺點(diǎn)由于java的內(nèi)存模型的原因偶爾會(huì)失敗;推薦使用volatile關(guān)鍵字,將對(duì)像直接寫入主內(nèi)存,會(huì)影響性能,但是會(huì)保證程序的準(zhǔn)確性。
4.靜態(tài)內(nèi)部類實(shí)現(xiàn)單例模式
public class Person {
private static volatile Person instance;
private Person() {}
public static Person getInstance(){
return PersonHolder.instance;
}
//靜態(tài)內(nèi)部類
private static class PersonHolder {
private static final Person instance = new Person();
}
}
優(yōu)點(diǎn):
1)第一次加載Person不會(huì)初始化;
2)第一次加載getInstance()導(dǎo)致虛擬機(jī)加載PersonHolder類,才會(huì)進(jìn)行類的初始化;
3)可以保證線程安全,以及單例的唯一性;
4)延遲了類的實(shí)例化,推薦使用該方法。
五、android源碼中的實(shí)現(xiàn)
- 1.Context
- 2.LayoutInflater
- 3.PolicyManager