首页 > 其他 > 详细

单例模式实现

时间:2017-09-06 21:18:41      阅读:241      评论:0      收藏:0      [点我收藏+]
  1. 静态内部类(static nested class) 优先考虑
  2.  
  3. public class LazySingleton{  
  4.     private LazySingleton(){}  
  5.   
  6.     private static class Nested{  
  7.         private static final LazySingleton single = new LazySingleton();  
  8.     }  
  9.   
  10.     public static LazySingleton getInstance(){  
  11.         return Nested.single;  
  12.     }  
  13. }  

双重检查锁定(DCL)

  1. public class LazySingleton{  
  2.     private LazySingleton(){}  
  3.   
  4.     private static volatile LazySingleton single = null;  
  5.   
  6.     public static LazySingleton getInstance(){  
  7.         if(single == null){  
  8.             synchronized (LazySingleton.class){  
  9.                 if(single == null){  
  10.                     single = new LazySingleton();   //① 非原子操作  
  11.                 }  
  12.             }  
  13.         }   
  14.         return single;  
  15.     }  
  16. }  

单例模式实现

原文:http://www.cnblogs.com/sjqq/p/7486807.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!