單例模式實現對比

weixin_34326429發表於2018-05-22

參考連結: 單例模式

一、實現對比

推薦指數 實現方式 多執行緒安全 Lazy初始化 實現難度 記憶體消耗 執行效率 JDK版本
**** 列舉 1.5+
**** 餓漢式 -
*** 靜態內部類 一般 -
** 雙檢鎖/雙重校驗鎖(DCL) 複雜 1.5+
* 懶漢式(非執行緒安全) -
* 懶漢式(執行緒安全) 極低 -

二、實現方式

懶漢式(非執行緒安全)

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

懶漢式(執行緒安全)

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

[推薦] 餓漢式

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

Classloder機制避免了多執行緒的同步問題

雙檢鎖/雙重校驗鎖(DCL)

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

[推薦] 靜態內部類

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

Classloder機制避免了多執行緒的同步問題

[推薦] 列舉

    public enum Singleton {  
        INSTANCE; 
         
        public static Singleton getInstance() {
            return INSTANCE;
        }

        public void method() {  
        }  
    }  

相關文章