Singleton设计模式,需要双重检查吗?

Posted on 2010-03-03 22:35  FreeSkyCD  阅读(140)  评论(0编辑  收藏  举报

Singleton设计模式,双重检查样列如下:

  • public class Singleton   
  • {   
  •     private static final Singleton singleton = null;   
  •   
  •     private Singleton()   
  •     {   
  •     }   
  •     public static Singleton getInstance()   
  •     {   
  •         if (singleton== null)   
  •         {   
  •             synchronized (Singleton.class)   
  •             {   
  •                 if (singleton== null)   
  •                 {   
  •                     singleton= new Singleton();   
  •                 }   
  •             }   
  •         }   
  •         return singleton;   
  •     }   
  • }  
  •  

    简单样列1:

    public class Singleton { 
     private final static Singleton instance=new Singleton();
     private Singleton(){}
     public static Singleton getInstance(){ 
      return instance; 
     }
    }

     

    双重检查很通用,但是它引以为傲的是性能的优化(在getInstance被很多很多次调用的情况下).

    呵呵,我就直接说结论了:在性能上最优的是 简单样列1 [当然也是在getInstance被很多很多次调用的情况下].

    简单样列1是非惰性加载,所以有人要反驳说 如果我不用到Singleton 的实例岂不是白占了内存.

    所以你选择 简单样列1 还是 双重检查 是要根据你的实际情况的,如果在程序中对单列类引用的频率是很高的,那么应该选择 简单样列1,反之 双重检查.

     

     

     



    已有 0 人发表留言,猛击->>这里<<-参与讨论


    JavaEye推荐



    Copyright © 2024 FreeSkyCD
    Powered by .NET 8.0 on Kubernetes