3 设计模式之单例模式

单例模式

单例模式,该模式也是一种对象的创新方式。当全局对象只需要一个实例时,就可以使用单例模式。

单例模式的创建方式

饿汉式

该模式是对象在类加载的时候就直接被实例化

举例

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

懒汉式

该模式是对象在被使用时实例化,也就是按需加载。为了线程安全,对象的创建方式常用的有:双检索方式和通过静态内部类创建。

举例

双检锁方式

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

静态内部类方式

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

优缺点

优点

  • 避免多实例造成的内存浪费
  • 避免多实例导致的逻辑错误

缺点

  • 饿汉式:程序构建时间过长。
  • 懒汉式:程序运行时构建,用户使用体验不流畅

使用场景

  • 当实例构建简单,且构建后直接使用,使用饿汉式。
  • 当实例构建复杂,且构建后偶尔使用,使用懒汉式。
posted @ 2021-01-01 21:58  lecy6  阅读(104)  评论(0)    收藏  举报