深入单例模式一(转)

参考: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()方法可能会出现问题,如何才能做到线程安全呢,可以将代码变成:

扫描二维码关注公众号,回复: 278701 查看本文章
[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. }  

猜你喜欢

转载自bugyun.iteye.com/blog/2297412
今日推荐