單例模式

保證程序中只有一個(gè)對(duì)象,但可以全局訪問。適用于創(chuàng)建消耗大、時(shí)間長、占用資源大的對(duì)象。


靜態(tài)代碼塊自動(dòng)執(zhí)行。
靜態(tài)方法被調(diào)用才執(zhí)行。
static加給單例對(duì)象,保證全局只有一個(gè)單例。

  • 餓漢式
    初始化就用到單例,使用對(duì)象加載快的情況。
class void Singleton{
     private static Singleton instance = new Singleton();

      private Singleton(){}
     
      public static Singleton getInstance(){
            return instance;
      }
}
  • 懶漢式
    等需要時(shí)候再加載,避免內(nèi)存浪費(fèi)。
class void Singleton{
      private static Singleton instance = null;

      private Singleton(){}

      public static Singleton getInstance(){
            if(instance == null)
                  instance = new Singleton();
            return instance;
      }
}

多線程下的單例模式
①餓漢式無影響,因?yàn)轭愒谘b載是就分配好內(nèi)存。
②懶漢式在創(chuàng)建對(duì)象時(shí)可能有多個(gè)線程同時(shí)在創(chuàng)建,不能保證全局唯一對(duì)象。

  • 雙重鎖定
    在懶漢式的基礎(chǔ)上加上類鎖,保證多線程下的安全。
public class Singleton{
      private static volatile Singleton instance = null;

      private Singleton(){}

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

volatile是為了每個(gè)線程讀取instance都是從主存中讀取最新的instance狀態(tài)。

第一次判斷instance == null 這是為了在instance已經(jīng)實(shí)例化后下次進(jìn)入不必執(zhí)行synchronized (Singleton.class)獲取對(duì)象鎖,從而提高性能。
第二次判斷instance == null 是為了判斷其他線程是否已經(jīng)實(shí)例化了該對(duì)象,避免重復(fù)實(shí)例化。

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

靜態(tài)內(nèi)部類在被調(diào)用時(shí)才會(huì)加載。
JVM在類加載時(shí)會(huì)保證同步

public class Singleton{ 
     private static class SingletonHolder{ 
           public static Singleton instance = new Singleton(); 
     } 

     private Singleton(){} 

     public static Singleton newInstance(){ 
           return SingletonHolder.instance; 
     } 

     public void doSomething(){ }
}
  • 枚舉
    這是現(xiàn)在為止官方最為推薦的單例模式的寫法,但是不推薦在Android中使用,因?yàn)闀?huì)比其他static對(duì)象多兩倍的內(nèi)存使用。
public enum Singleton{ 
      //定義一個(gè)枚舉的元素,它就是Singleton的一個(gè)實(shí)例 instance; 

      public void doSomething(){} 
}

使用

Singleton singleton = Singleton.instance; 
singleton.doSomething();
最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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