美文网首页
单例模式实现对比

单例模式实现对比

作者: Jimmy_gjf | 来源:发表于2018-05-22 14:50 被阅读23次

    参考链接: 单例模式

    一、实现对比

    推荐指数 实现方式 多线程安全 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() {  
            }  
        }  
    

    相关文章

      网友评论

          本文标题:单例模式实现对比

          本文链接:https://www.haomeiwen.com/subject/yxsfjftx.html