zoukankan      html  css  js  c++  java
  • 单例模式

    1分类

      常见的单例设计模式有饿汉式、懒汉式、同步懒汉式、双重锁 校验懒汉式、静态内部类饿汉式 

    2代码

      1饿汉式                    

      优点:线程安全,效率较高                    

      缺点:不支持懒加载                    

      总结:开发中推荐使用

        public class Singleton {

            private static Singleton instance = new Singleton();

            private Singleton (){}

            public static Singleton getInstance() {

                return instance;

            }

        }

      2懒汉式

      优点:支持懒加载                    

      缺点:线程不安全、效率低                    

      总结 :开发中不推荐使用

        public class Singleton {

            private static Singleton instance;

            private Singleton (){}

            public static Singleton getInstance() {

                if (instance == null) {

                    instance = new Singleton();

                }

                return instance;

            }

        }

      3同步懒汉式                    

      优点:线程安全,支持懒加载                    

      缺点:效率低下                    

      总结:解决了普通懒汉式的线程不安全问题,不推荐。                    

      public class Singleton {

           private static Singleton instance;

           private Singleton (){}

              public static synchronized Singleton getInstance() {

                if (instance == null) {

                    instance = new Singleton();

                }

                return instance;

            }

      }

      4双重锁校验懒汉式                    

      优点:线程安全,支持懒加载,效率高。                    

      总结:开发中推荐使用。                     

      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;

         }

      5静态内部类饿汉式     

      优点:线程安全,支持懒加载,效率高。                    

      总结:开发中推荐使用。           

      public class Singleton {

           private static class SingletonHolder {

               private static final Singleton INSTANCE = new Singleton();

           }

           private Singleton (){}

           public static final Singleton getInstance() {

               return SingletonHolder.INSTANCE;

           }

      }

    3.总结

      在开发中,推荐大家使用饿汉式、双重锁校验懒汉式、静态内部类饿汉式。但是以上三种单例设计模式,依然存在致命缺陷,至于是什么缺陷,请关注软谋公众号,相关问题我们将在下一期文章中给出解决方案

     

  • 相关阅读:
    cookies
    php文件上传
    pho文件和目录操作
    php 日期和时间
    json解析网站
    only_full_group_by的注意事项
    $.extend()、$.fn和$.fn.extend()
    select样式美化(简单实用)
    toArray(),toJson(),hidden([ ]),visible([ ])
    tp5 model 中的查询范围(scope)
  • 原文地址:https://www.cnblogs.com/sunBinary/p/9828543.html
Copyright © 2011-2022 走看看