【任推薦】單例模式的最佳實現



 

public  class Singleton {
         //  Private constructor prevents instantiation from other classes
         private Singleton() { }
 
         /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        
*/
         private  static  class SingletonHolder { 
                 public  static  final Singleton INSTANCE =  new Singleton();
        }
 
         public  static Singleton getInstance() {
                 return SingletonHolder.INSTANCE;
        }

 

 

99%的Java程序員實現不了一個完美的單例模式,看看Wiki上給出的最佳實現:http://t.cn/zOvZMy3 通過單例模式全面了解Double-checked locking以及並發時候的鎖的問題:http://t.cn/aKbmIb 

 ——(Java性能優化群243242580
聊天記錄)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM