整理下java六種單例模式

console發表於2019-01-19

可能總結的會有問題,我會一點點完善的…

結論:建議使用第 4 種餓漢方式。如果明確要實現懶載入效果時,使用第 5 種靜態內部類方式。如果涉及到反序列化建立物件時,可以使用第 6 種列舉方式。

1 懶漢式,執行緒不安全

public class Singleton {

    private static Singleton instance=null;
    
    public static Singleton getInstance(){
        if(instance==null){
            instance=new Singleton();
        }
        return instance;
    }
    
     private Singleton(){}
}

2 懶漢式,執行緒安全

public class Singleton {

    private static Singleton instance=null;
    
    public static synchronized Singleton getInstance(){
        if(instance==null){
            instance=new Singleton();
        }
        return instance;
    }
    
    private Singleton(){}
}

3 雙重檢查鎖,懶漢式,執行緒安全

public class Singleton {

    private volatile static Singleton instance=null;
    
    public static Singleton getInstance(){
        if(instance==null){
            synchronized(Singleton.class){
                if(instance==null){
                    instance=new Singleton();
                }
            }
        }
        return instance;
    }
    
            
    private Singleton(){}
}

4 餓漢式,執行緒安全

public class Singleton {

    private static Singleton instance=new Singleton();
    
    public static Singleton getInstance(){
        return instance;
    }
    
    private Singleton(){}
}

5 靜態內部類,懶漢式,執行緒安全

public class Singleton {
    
    private static class SingletonHolder{
        private final static Singleton instance=new Singleton();
    }
    
    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
    
    private Singleton(){}
}

6 列舉類,懶漢式,執行緒安全

public enum SingletonEnum{
    INSTANCE;
}

相關文章