Java設計模式之單例模式(七種寫法)

來源:互聯網
上載者:User

標籤:eve   ext   ola   log   情況下   null   內部類   center   靜態內部類   

Java設計模式之單例模式(七種寫法)

第一種,懶漢式,lazy初始化,線程不安全,多線程中無法工作:
public class Singleton {    private static Singleton instance;    private Singleton (){}//私人化構造方法,防止類被執行個體化    public static Singleton getInstance() {    if (instance == null) {        instance = new Singleton();    }    return instance;    }}
第二種,懶漢式,lazy初始化,安全執行緒:
  • 優點:第一次調用才初始化,避免記憶體浪費。
  • 缺點:必須加鎖 synchronized 才能保證單例,但加鎖會影響效率。
public class Singleton {    private static Singleton instance;      private Singleton (){}      public static synchronized Singleton getInstance() {      if (instance == null) {          instance = new Singleton();      }      return instance;      }  }  
第三種,餓漢式,不是lazy初始化,安全執行緒:
  • 優點:沒有加鎖,執行效率會提高。
  • 缺點:類載入時就初始化,浪費記憶體。
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;    }  }  
第五種,靜態內部類,lazy初始化,安全執行緒:

區別第三種,Singleton 類被裝載了,instance 不一定被初始化。因為 SingletonHolder 類沒有被主動使用;只有通過顯式調用 getInstance 方法時,才會顯式裝載 SingletonHolder 類,從而執行個體化 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() {      }  } 
第七種,雙重校正鎖DCL(double-checked locking),lazy初始化,安全執行緒:

JDK1.5 起,採用雙鎖機制,安全且在多線程情況下能保持高效能。
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;    }  }  

 

Java設計模式之單例模式(七種寫法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.