設計模式-單例模式

//單例餓漢
public class Singleton01 {
    private static final Singleton01 INSTANCE = new Singleton01();

    private Singleton01() {
    }

    public static Singleton01 getInstance() {
        return INSTANCE;
    }
}
public class Singleton02 {
    private volatile static Singleton02 INSTANCE;
    //爲何要使用volatile
    //執行構造方法和賦值的操做可能會指令重排序,併發狀況下可能有兩個對象被初始化
    //故使用volatile,禁止指令重排序,保證線程安全
    private Singleton02() {}

    public static Singleton02 getInstance() {
        if (INSTANCE == null) {
            synchronized (Singleton02.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton02();
                }
            }
        }
        return INSTANCE;
    }
}
public class Singleton03 {
    private Singleton03() {
    }
    //靜態內部類自帶懶加載
    private static class SingletonHolder {
        private static Singleton03 INSTANCE = new Singleton03();
    }

    public static Singleton03 getInstance() {
        return SingletonHolder.INSTANCE;
    }

}
public enum Singleton04 {
    //枚舉
    INSTANCE;
}
相關文章
相關標籤/搜索