设计模式_五种单例模式

五种单例实现:

(1)饿汉模式:(线程安全,调用率高,但是不能延时加载)

      public class Singleton1{

           //类初始化时就立即加载对象(没有延迟加载的优势),天然的线程安全。
           private static Singleton1 singleton1 = new Singleton1();
           private Singleton1() {
               //构造方法私有化
           }
           //方法没有同步,调用效率高
           public static Singleton1 getInstance(){
               return singleton1;
           }
       }   

(2)懒汉模式:(线程安全,调用率不高,但是可以延时加载)

       public class Singleton2{
            private static Singleton2 singleton2;
            private Singleton2(){
                //构造方法私有化
            }
            public synchronized static Singleton2 getInstance2(){
                if(singleton2 == null){
                    singleton2 = new Singleton2();
                }
                return singleton2();
            }
        }

(3)双重检测锁模式:(由于JVM底层模型问题,偶尔会出问题,不建议使用)

        public class Singleton3{
            private volatile static Singleton3 singleton3;
            private Singleton3(){
                //构造私有化
            }
            public static Singleton3 getInstance3(){
                if(singleton3 == null){
                    synchronized (Singleton3.class){
                        if(singleton3 == null){
                            singleton3 = new Singleton3();
                        }
                    }
                }
                return singleton3;
            }
        }

(4)静态内部类模式:(线程安全,调用率高,可以延时加载)

  • 通过内部类机制使得单例对象可以延迟加载,同时内部类相当于是外部类的静态部分,所以可以通过JVM来保证线程安全
      public class Singleton4{
            private static class Singleton4Holder{
                private static Singleton4 singleton4 = new Singleton4();
            }
            private Singleton4(){
                //构造私有化
            }
            public static Singleton4 getInstance(){
                return Singleton4Holder.singleton4;
            }

        }

(5)枚举模式:(线程安全,调用率高,不能延时加载,但是可以天然防止反射和反序列化调用)

    public enum Singleton5{
            singleton5
    }
}
发布了120 篇原创文章 · 获赞 59 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/lr1916417519/article/details/94361193