深入单例模式一(转)

参考:http://blog.csdn.net/mrfly/article/details/13372441

 

单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点,可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制,“阻止”所有想要生成对象的访问。使用工厂方法来限制实例化过程。这个方法应该是静态方法(类方法),因为让类的实例去生成另一个唯一实例毫无意义。

 

 

 

 

饿汉式代码如下:

 

[java]  view plain  copy
 
  1. package zhaodp.demo;  
  2.   
  3. public class Singleton {  
  4.     private static Singleton uniqueInstance = null;  
  5.     public static Singleton instance(){  
  6.         if(uniqueInstance == null)  
  7.             uniqueInstance = new Singleton();  
  8.         return uniqueInstance;  
  9.     }  
  10. }  

 

设计模式的教科书上的示例一般与上述代码类似。如果在多线程环境下,instance()方法可能会出现问题,如何才能做到线程安全呢,可以将代码变成:

[java]  view plain  copy
 
  1. public synchronized static Singleton instance(){  
  2.     if(uniqueInstance == null)  
  3.         uniqueInstance = new Singleton();  
  4.     return uniqueInstance;  
  5. }  

将instance方法加上synchronized进行限定,确实可以解决线程安全问题,但会造成多线程调用该方法时串行执行,效率低下,如何改进呢?以下代码既可以保证线程安全又可以提高多线程并发的效率。

[java]  view plain  copy
 
  1. package zhaodp.demo;  
  2.   
  3. public class Singleton {  
  4.     private static Singleton uniqueInstance = null;  
  5.   
  6.     public static Singleton instance() {  
  7.         if (uniqueInstance != null)  
  8.             return uniqueInstance;  
  9.         synchronized (Singleton.class) {  
  10.             if (uniqueInstance == null)  
  11.                 uniqueInstance = new Singleton();  
  12.         }  
  13.         return uniqueInstance;  
  14.     }  
  15. }  


 

或者这么写:

[java]  view plain  copy
 
  1. package zhaodp.demo;  
  2.   
  3. public class Singleton {  
  4.     private static Singleton uniqueInstance = null;  
  5.   
  6.     public static Singleton instance() {  
  7.         if (uniqueInstance == null) {  
  8.             synchronized (Singleton.class) {  
  9.                 if (uniqueInstance == null)  
  10.                     uniqueInstance = new Singleton();  
  11.             }  
  12.         }  
  13.         return uniqueInstance;  
  14.     }  
  15. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值