详解单例模式六种写法的优缺点

前言

单例模式:保证一个类有且仅有一个实例. 通过定义我们可知它是创建型的一种, 也是比较简单的一种
单例模式的使用场景: 频繁的进行创建和销毁的对象、创建对象时消耗过多或者消费资源过多,但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象.

下面主要分析一下单例模式的六种写法, 以及优缺点!

  • 饿汉式(静态常量)
  • 懒汉式(线程不安全)
  • 懒汉式(线程安全)
  • 双重检查
  • 静态内部类
  • 枚举

饿汉式(静态常量)

代码

//饿汉式(静态常量)
class Singleton {
    // 构造器私有 外部不能实例化
    private Singleton() {
    }
    private final static Singleton instance = new Singleton();
    public static Singleton getInstance() {
        return instance;
    }
}

优点

  • 写法简单, 在类装载的时候完成了实例化
  • 避免了线程同步问题

缺点

  • 导致类装载的原因有很多种, 不能达到 lazy loading(懒加载)的效果
  • 有可能造成内存浪费

懒汉式(线程不安全)

代码

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

优点

  • 起到了 lazy loading(懒加载)的效果

缺点

  • 虽然起到了 lazy loading(懒加载)的效果, 但是只能在单线程的情况下使用
  • 线程不安全, 实际开发中不建议使用这种方式

懒汉式(线程安全)

代码

//懒汉式(线程安全,同步方法)
class Singleton{
    private static Singleton instance;
    private Singleton(){}
    public static synchronized Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

优点

  • 解决了线程安全
  • 起到了lazy loading(懒加载)的效果

缺点

  • 效率太低了, 这个方法只执行一次实例化代码就够了, 但是每个线程都要同步, 方法进行同步的效率太低
  • 在实际开发中, 不建议使用

双重检查

代码

//双重检查(线程安全  实现了懒加载  同时保证了效率)
class Singleton {
    private static volatile Singleton instance;

    private Singleton() {
    }

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

优点

  • 解决了线程安全
  • 起到了lazy loading(懒加载)的效果
  • 在实际开发中, 建议使用

静态内部类

代码

//静态内部类
class Singleton{
    private Singleton(){}
    private static class SingletonInstance{
        private static final Singleton INSTANCE= new Singleton();
    }
    public static synchronized Singleton getInstance(){
        return SingletonInstance.INSTANCE;
    }
}

优点

  • 解决了线程安全, 静态属性置灰在第一次加载类的时候初始化, jvm帮我们保证了线程的安全
  • 起到了lazy loading(懒加载)的效果
  • 在实际开发中, 建议使用

枚举

enum Singleton{
    INSTANCE;
    test t;
    private Singleton(){
       t = new test();
    }
    public test getTest(){
        return t;
    }
}
class test{
}

优点

  • 解决了线程安全, 而且泛能防止反序列化重新创建新的对象
  • 起到了lazy loading(懒加载)的效果
  • 在实际开发中, 建议使用

总结

设计模式真的是前辈们总结出来的精髓, 代表了最佳的实践, 还是需要继续的深入学习和理解里面的奥妙.

发布了142 篇原创文章 · 获赞 208 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/ywq1016243402/article/details/103943659