設計模式之單例模式

一、概論

1.所謂單例就是隻有一個實例(對象),

2實現的思路是將構造方法私有化,對外提供一個獲取該實例的靜態方法,(有則返回,無則創建再返回)

3.其他類就可以根據這個對象調用這個類中的方法。

二、爲什麼要學習單例模式

1.解決資源共享和資源控制相關問題,如:網站計數器,windows的任務管理器、垃圾回收站,日誌等

2.全局使用的類的實例頻繁的創建和銷燬,耗用大量不必要的系統資源

三、幾種實現方式的實例代碼

1.懶漢式(非線程安全)

   特點:屬於懶加載(具體需要時才實例化),非線程安全,

  實例代碼:

/**
 * 懶漢式,線程不安全,不支持多線程,沒有加synchronized
 */
public class Singleton1 {
    private static Singleton1 singleton1;
    private Singleton1(){}//構造方法私有,其他類無法實例化
    //對外提供一個獲取該實例對象的方法
    public static Singleton1 getInstance(){
        if (singleton1 == null){
            singleton1 = new Singleton1();
        }
        return singleton1;
    }
    //以下定義多個共享的方法
    public void display(){}
}

2.懶漢式(線程安全)

   特點:懶加載,線程安全

   實例代碼:

public class Singleton2 {
    
    private static Singleton2 singleton2;
    
    private Singleton2(){}
    
    public static synchronized Singleton2 getInstance2(){
        if (singleton2 == null){
            singleton2 = new Singleton2();
        }
        return singleton2;
    }
    //其他共享方法
    public void otherMethod(){}
}

3.餓漢式

   特點:非懶加載,線程安全

  實例代碼:

public class Singleton3 {
    private static Singleton3 singleton3 = new Singleton3();
    private Singleton3 (){}
    public static Singleton3 getInstance3(){
        return singleton3;
    }
}

4.雙重檢驗鎖方式

   特點:懶加載,線程安全

  實例代碼:

/**
 * 雙重檢驗鎖,多線程下高性能
 */
public class Singleton4 {
    private volatile static Singleton4 singleton4;
    private Singleton4(){}
    public static Singleton4 getInstance4(){
        if (singleton4 == null){
            synchronized (Singleton4.class){
                if (singleton4 ==null){
                    singleton4 = new Singleton4();
                }
            }
        }
        return singleton4;
    }
}

5.內部類方式

  特點:懶加載,線程安全

  實例代碼:

/**
 * 靜態內部類方式
 */
public class Singleton5 {
    //內部類
    private static class Singleton{
        private static final Singleton5 singleton = new Singleton5();
    }
    private Singleton5(){}
    public static final Singleton5 getInstance5(){
        return Singleton.singleton;
    }
}

//以上內容來源於網絡,純屬個人學習做記錄,歡迎大家批准、指正、提議!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章