课程大纲 / Lesson 06
Singleton 创建型

Singleton · 单例

确保一个类只有一个实例,并提供一个全局访问点。

01

理解单例模式:确保一个类在整个程序生命周期中只有一个实例

02

掌握懒汉式、饿汉式、双重检查锁等不同实现方式的优缺点

03

理解单例模式在多线程环境下的线程安全问题

04

了解单例模式的适用场景和潜在问题(全局状态、隐藏依赖)

核心概念
唯一实例全局访问线程安全延迟加载私有构造函数
classDiagram class singleton { -instance singleton$ -singleton() +getinstance() singleton$ +dobusinesslogic() } singleton --> singleton : returns single instance

私有构造器阻止外部实例化,全局访问点始终返回同一实例

点击 Run 观察线程获取单例...
/** 双重检查锁单例实现(线程安全 + 延迟加载) */
public class Singleton {
    private volatile static Singleton instance;

    /** 私有构造函数,防止外部 new */
    private Singleton() {}

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

    public void doBusinessLogic() {
        System.out.println("Business logic executed");
    }
}
/** 多线程场景下验证单例唯一性 */
public class DemoMultiThread {
    public static void main(String[] args) throws InterruptedException {
        Singleton[] instances = new Singleton[2];
        Thread t1 = new Thread(() ->
            instances[0] = Singleton.getInstance());
        Thread t2 = new Thread(() ->
            instances[1] = Singleton.getInstance());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Thread-1 instance == Thread-2 instance: "
            + (instances[0] == instances[1]));
    }
}
◈

私有构造函数是核心

单例通过私有构造函数防止外部 new,确保所有调用都通过 getInstance() 获取同一实例。

◈

双重检查锁实现线程安全

volatile 修饰 instance + synchronized 双重检查,既保证线程安全又避免每次 getInstance() 都加锁的性能损耗。

◈

延迟加载(懒加载)

相比饿汉式(类加载时即创建实例),双重检查锁单例在首次调用时才创建,节省资源。

◈

适用场景与潜在问题

适合:全局配置、数据库连接池、线程池。问题:全局状态导致测试困难、隐藏依赖、违背单一职责原则。