Singleton 的較好的實現方法

1. 靜態持有者單例模式(static holder singleton pattern) html

public static class Singleton {
    private static class InstanceHolder {
        public static Singleton instance = new Singleton();
    }

    private Singleton(){}

    public static Singleton getInstance() { 
        return InstanceHolder.instance;
    }
}

有三個好處:java

第一,靜態工廠;第二,延遲初始化;第三,線程安全。安全

2. 雙重檢查鎖(singleton with double checked locking)線程

public class Singleton {
    private Singleton(){
    }

    private static Singleton instance;
    
    public static Singleton getInstance() {
        if (instance == null) {                // Single checked
            synchronized (Singleton.class) {
                if (instance == null) {        // Double checked
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

參考文獻code

3. 使用枚舉 (Making singletons with Enum in Javahtm

public enum EnumSingleton {
    INSTANCE;
 
    // other methods...
}

Why Enum Singleton are better in Javablog

相關文章
相關標籤/搜索