确保一个类只有一个实例,并提供一个全局访问点。
理解单例模式:确保一个类在整个程序生命周期中只有一个实例
掌握懒汉式、饿汉式、双重检查锁等不同实现方式的优缺点
理解单例模式在多线程环境下的线程安全问题
了解单例模式的适用场景和潜在问题(全局状态、隐藏依赖)
私有构造器阻止外部实例化,全局访问点始终返回同一实例
/** 双重检查锁单例实现(线程安全 + 延迟加载) */
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() 都加锁的性能损耗。
相比饿汉式(类加载时即创建实例),双重检查锁单例在首次调用时才创建,节省资源。
适合:全局配置、数据库连接池、线程池。问题:全局状态导致测试困难、隐藏依赖、违背单一职责原则。