【116、单例模式有几种写法?】

81 阅读1分钟

单例模式是一种常见的设计模式,它的主要目的是确保一个类只有一个实例,并提供全局访问点。单例模式的实现方式有以下几种:

  1. 懒汉式(线程不安全)

这种写法在类加载的时候不会创建实例,而是在第一次调用 getInstance() 方法时才创建实例,存在线程安全问题。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 懒汉式(线程安全)

这种写法在 getInstance() 方法中使用 synchronized 关键字对代码块进行加锁,确保了线程安全,但是性能较低。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 饿汉式

这种写法在类加载的时候就创建实例,不存在线程安全问题,但是可能会浪费一些内存空间。

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

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}
  1. 双重校验锁

这种写法在 getInstance() 方法中使用双重校验锁,既保证了线程安全,又提高了性能。

public class Singleton {
    private volatile static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. 静态内部类

这种写法在 Singleton 类中定义了一个静态内部类 SingletonHolder,用于延迟初始化 Singleton 实例,同时保证了线程安全和懒加载。

public class Singleton {
    private Singleton() {}

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

总的来说,单例模式的实现方式有很多种,选择哪一种方式取决于具体的应用场景和需求。