2020-11-18 單例模式

概念

單例模式:是一種對(duì)象創(chuàng)建型模式,用來(lái)確保程序中一個(gè)類(lèi)最多只有一個(gè)實(shí)例,并提供訪問(wèn)這個(gè)實(shí)例的全局點(diǎn)。

單例模式的解決方案

  • 隱藏類(lèi)的構(gòu)造方法,用private修飾符修飾構(gòu)造方法.
  • 定義一個(gè)public的靜態(tài)方法(getInstance()) ,返回這個(gè)類(lèi)唯一靜態(tài)實(shí)例。

雙重檢查的單例模式


public class Singleton {  
    private volatile Singleton instance = null;   
    public Singleton getInstance() {  
        if (instance == null) {  
            synchronized(this) {  
                if (instance == null) {  
                    instance = new Singleton();  
                }  
            }  
        }  
        return instance;  
    }  
}  

關(guān)鍵字volatile 保證多線程下的單例:原因:https://blog.csdn.net/shadow_zed/article/details/79650874
原理:https://blog.csdn.net/anjxue/article/details/51038466?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control
推薦方法:

public class Singleton {  
   
private Singleton () {};
 
    static class SingletonHolder {  
        static Singleton instance = new Singleton();  
    }  
      
    public static Singleton getInstance(){  
        return SingletonHolder.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)容