單例設(shè)計(jì)模式

1.懶漢式 線程不安全,當(dāng)有多個(gè)線程并行調(diào)用getInstance()的時(shí)候,就會(huì)創(chuàng)建多個(gè)實(shí)例。也就是說(shuō)在多線程下不能正常工作。

public class Singleton{

private static Singleton instance;

private Singleton(){}

public static Singleton getInstance(){

if(instance == null){

instance = new Singleton();

? ? }

return instance;

}

}

2.懶漢式 線程安全,雖然做到了線程安全,并且解決了多實(shí)例的問(wèn)題,但是它并不高效。因?yàn)樵谌魏螘r(shí)候只能有一個(gè)線程調(diào)用getInstance()方法。但是同步操作只需要在第一次調(diào)用時(shí)才被需要,即第一次創(chuàng)建單例實(shí)例對(duì)象時(shí)。這就引出了雙重檢驗(yàn)鎖。

public class Singleton{

private static Singleton instance;

private Singleton(){}

public synchronized static Singleton getInstance(){

if(instance == null){

instance = new Singleton();

}

return instance;

}

}

3.雙重檢驗(yàn)鎖

public static Singleton getSingleton() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton();

}

}

}

return instance ;

}

>改進(jìn)代碼, instance 變量聲明成 volatile

public class Singleton {

private volatile static Singleton instance; //聲明成 volatile

private Singleton (){}

public static Singleton getSingleton() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton();

}

}

}

return instance;

}

}

4.餓漢式,在第一次加載類到內(nèi)存中時(shí)就會(huì)初始化,所以創(chuàng)建實(shí)例本身是線程安全的。

public class Singleton {

//類加載的時(shí)候就初始化

private static final Singleton instance =? new Singleton();

private Singleton(){}

public static Singleton getInstance() {

return instance;

}

}

5.靜態(tài)內(nèi)部類.

public class Singleton {

private static class SingletonHolder{

private static final INCTANCE = new Singleton();

}

private Singleton(){}

public static final Singleton getInstance(){

return SingletonHolder.INSTANCE;

}

}

6.枚舉

public enum EasySingleton {

INSTANCE;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容