单例模式实现对比

参考链接: 单例模式

一、实现对比

推荐指数 实现方式 多线程安全 Lazy初始化 实现难度 内存消耗 执行效率 JDK版本
**** 枚举 1.5+
**** 饿汉式 -
*** 静态内部类 一般 -
** 双检锁/双重校验锁(DCL) 复杂 1.5+
* 懒汉式(非线程安全) -
* 懒汉式(线程安全) 极低 -

二、实现方式

懒汉式(非线程安全)

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

懒汉式(线程安全)

    public class Singleton {  
        private static Singleton instance;  
        private Singleton (){}  
        
        public static synchronized Singleton getInstance() {  
               if (instance == null) {  
                   instance = new Singleton();  
               }  
               return instance;  
        }  

[推荐] 饿汉式

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

Classloder机制避免了多线程的同步问题

双检锁/双重校验锁(DCL)

    public class Singleton {  
        private volatile static Singleton singleton;  
        private Singleton (){} 
         
        public static Singleton getSingleton() {  
              if (singleton == null) {  
                  synchronized (Singleton.class) {  
                        if (singleton == null) {  
                            singleton = new Singleton();  
                        }  
                  }  
              }  
              
              return singleton;  
        }  
    } 

[推荐] 静态内部类

    public class Singleton {  
    
        private static class SingletonHolder {  
                private static final Singleton INSTANCE = new Singleton();  
        }  
        
        private Singleton (){}  
        
        public static final Singleton getInstance() {  
               return SingletonHolder.INSTANCE;  
        }  
    }

Classloder机制避免了多线程的同步问题

[推荐] 枚举

    public enum Singleton {  
        INSTANCE; 
         
        public static Singleton getInstance() {
            return INSTANCE;
        }

        public void method() {  
        }  
    }  
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容