码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式实现

时间:2017-09-06 21:26:57      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:nes   keyword   stat   singleton   star   instance   优先   art   静态   

  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. }  

单例模式实现

标签:nes   keyword   stat   singleton   star   instance   优先   art   静态   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!