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推荐



    相关文章:

    • 2022-12-23
    • 2021-06-17
    • 2021-08-18
    • 2021-05-20
    • 2021-07-03
    • 2021-09-10
    • 2022-12-23
    • 2021-07-16
    猜你喜欢
    • 2022-01-27
    • 2019-08-15
    • 2022-12-23
    • 2021-06-05
    • 2022-03-12
    • 2022-02-26
    • 2021-06-13
    相关资源
    相似解决方案