Java設(shè)計(jì)模式之單例模式(七種寫法)

第一種,懶漢式,lazy初始化,線程不安全,多線程中無法工作:

public class Singleton {
    private static Singleton instance;
    private Singleton (){}//私有化構(gòu)造方法,防止類被實(shí)例化
    public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
    }
}

第二種,懶漢式,lazy初始化,線程安全:

  • 優(yōu)點(diǎn):第一次調(diào)用才初始化,避免內(nèi)存浪費(fèi)。
  • 缺點(diǎn):必須加鎖 synchronized 才能保證單例,但加鎖會(huì)影響效率。
public class Singleton {
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}  

第三種,餓漢式,不是lazy初始化,線程安全:

  • 優(yōu)點(diǎn):沒有加鎖,執(zhí)行效率會(huì)提高。
  • 缺點(diǎn):類加載時(shí)就初始化,浪費(fèi)內(nèi)存。
public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
        return instance;
    }  
} 

第四種,餓漢式,lazy初始化,線程安全:

public class Singleton {
    private Singleton instance = null;  
    static {  
        instance = new Singleton();
    }  
    private Singleton (){}  
    public static Singleton getInstance() {  
        return this.instance;
    }  
}  

第五種,靜態(tài)內(nèi)部類,lazy初始化,線程安全:

  • 區(qū)別第三種,Singleton 類被裝載了,instance 不一定被初始化。因?yàn)?SingletonHolder 類沒有被主動(dòng)使用;只有通過顯式調(diào)用 getInstance 方法時(shí),才會(huì)顯式裝載 SingletonHolder 類,從而實(shí)例化 instance。
public class Singleton {
   private static class SingletonHolder {  
       private static final Singleton INSTANCE = new Singleton();
   }  
   private Singleton (){}  
   public static final Singleton getInstance() {  
       return SingletonHolder.INSTANCE;
   }  
}  

第六種(枚舉),不是lazy初始化,線程安全:

public enum Singleton {
    INSTANCE;  
    public void whateverMethod() {  
    }  
}  

第七種,雙重校驗(yàn)鎖DCL(double-checked locking),lazy初始化,線程安全:

  • JDK1.5 起,采用雙鎖機(jī)制,安全且在多線程情況下能保持高性能。
public class Singleton {
    private volatile static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getSingleton() {  
        if (singleton == null) {
            synchronized (Singleton.class) {
            if (singleton == null) {
                singleton = new Singleton();
                }
            }
        }
        return singleton;
    }  
}  
  • 一般情況下建議使用第 3 種餓漢方式;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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