5、單例模式

來源:互聯網
上載者:User

標籤:安全執行緒   size   ble   ora   介紹   str   none   static   position   

  單例模式定義:確保一個類只有一個執行個體,並提供安全執行緒的訪問點。    以下介紹6中安全執行緒的單例模式
  • 立即載入模式/餓漢模式
  • 通過反射的方式可以獲得多個執行個體
public class Singleton1 {    private static Singleton1 singleton1 = new Singleton1();    private Singleton1() {    }    public static Singleton1 getSingleton() {        return singleton1;    }}
  • 使用靜態代碼塊實現單例模式
public class Singleton5 {    private static Singleton5 singleton5;    private Singleton5() {    }    static {        singleton5 = new Singleton5();    }    public static Singleton5 getSingleton() {        return singleton5;    }}
  • 消極式載入模式/懶漢模式
public class Singleton2 {    private static Singleton2 singleton2;    private Singleton2() {    }    public static synchronized Singleton2 getSingleton() {        if(singleton2==null) {            singleton2 = new Singleton2();        }        return singleton2;    }}
  • 使用靜態內部類方式
  • 如果遇到序列化對象時,還是可以獲得多個執行個體對象
public class Singleton3 {    private static class Singleton{        public static Singleton3 singleton= new Singleton3();    }    private Singleton3() {    }    public static Singleton3 getSingleton() {        return Singleton.singleton;    }}
解決靜態內部類通過序列化和反序列導致的多執行個體問題,如下:
public class Singleton3 implements Serializable {    private static final long serUID = 888L;    private static class Singleton{        public static Singleton3 singleton= new Singleton3();    }    private Singleton3() {    }    public static Singleton3 getSingleton() {        return Singleton.singleton;    }    protected Object readResolve() throws ObjectStreamException {        return Singleton.singleton;    }}
  • 使用枚舉類方式獲得單例
  • 枚舉類和靜態代碼塊特性相似,在使用枚舉類時,構造方法會被自動使用。
public enum Singleton6 {    singleton6;    private Singleton6(){    }    public Singleton6 getSingleton(){        return singleton6;    }}
  • 使用DCL雙檢查鎖機制,解決“消極式載入模式/懶漢模式”中使用synchronized鎖導致的效能問題;
public class Singleton4 {    private volatile static Singleton4 singleton4;    private Singleton4() {    }    public static Singleton4 getSingleton() {        if(singleton4==null) {            synchronized (Singleton4.class) {                singleton4 = new Singleton4();            }        }        return singleton4;    }}
 

5、單例模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.