設計模式之單例模式的7種寫法(源碼附上)

package com.kaka.test;

/**
 ** 單例使用場景 需要頻繁的進行創建和銷燬的對象; 
 * 
 **創建對象時耗時過多或耗費資源過多,但又經常用到的對象; 
 * 
 **工具類對象頻繁訪問數據庫或文件的對象。
 * 
 * @author KAKA
 *
 */
public class Singleton {
    // 餓漢式(常量類)
    private final static Singleton INSTANCE = new Singleton();
    private Singleton() {
    }

    public static Singleton getSingleton() {
        //類裝載的時候就完成實例化避免了線程同步問題
        return INSTANCE;
    }

    public static void main(String[] args) {
        getSingleton();
    }

    // 餓漢式(靜態常量)
    private static Singleton instance;

    static {
        instance = new Singleton();
    }

    // private Singleton(){}

    public static Singleton getinstance() {

        return instance;
    }

    // 懶漢式(靜態代碼塊)
    private static Singleton instance1;
    static {
        instance1 = new Singleton();
    }

//    private Singleton() {}
    public static Singleton getInstance1() {
        return instance1;
    }

    // 懶漢式(線程不安全)
    private static Singleton singleton2;

    // private Singleton() {}
    public static Singleton getsingleton2() {
        if (singleton2 == null) {
            singleton2 = new Singleton();
        }
        return singleton2;
    }

    // 懶漢式(線程安全,同步方法)
    private static Singleton singleton04;

    // private Singleton() {}
    public static synchronized Singleton getInstance() {
        if (singleton04 == null) {
            singleton04 = new Singleton();
        }
        return singleton04;
    }
    // 懶漢式(線程安全,同步代碼塊) 特點:效率低

    private static Singleton instance05;

    // private Singleton() {}
    public static Singleton getInstance05() {
        if (instance05 == null) {
            synchronized (Singleton.class) {
                instance05 = new Singleton();
            }
        }
        return instance05;
    }

    // 第6種 雙重檢查(推薦使用)
    private static volatile Singleton singleton06;

    // private Singleton() {}
    public static Singleton getSingleton06() {
        if (singleton06 == null) { // 第一次校驗線程
            synchronized (Singleton.class) {
                if (singleton06 == null) { // 第二次校驗線程
                    singleton06 = new Singleton();
                }
            }
        }
        // 線程安全,延遲加載,效率高
        return singleton06;
    }

    // 靜態內部類(推薦使用)
//    private Singleton() {}
    @SuppressWarnings("unused")
    private static class SingletonInstance {
        private static final Singleton INSTANCE07 = new Singleton();

        public static Singleton getInstance07() {
            // Singleton類被裝載時並不會立即實例化,而是在需要實例化時,
            // 調用getInstance方法,纔會裝載SingletonInstance類,從而完成Singleton的實例化
            return SingletonInstance.INSTANCE07;
        }

        // 枚舉型(推薦使用) jdk1.5
        // 優勢:避免多線程同步,還可以防止反序列化創建的新對象
        @SuppressWarnings("unused")
        public enum Singleton07 {
            INSTANCE07;
            public void getInstanceMethod() {
            }

        }
    }

}
 

發佈了29 篇原創文章 · 獲贊 22 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章