创建型-单例模式
2026/1/15大约 2 分钟Java设计模式创建型模式单例模式Java设计模式面向对象架构设计最佳实践代码优化
概述
单例模式(Singleton Pattern)确保一个类只有一个实例,并提供一个全局访问点。
适用场景
- 需要频繁创建和销毁的对象
- 创建对象耗时过多或耗费资源过多
- 工具类对象、频繁访问数据库或文件的对象
实现方式
1. 饿汉式(静态常量)
public class Singleton {
// 类加载时就初始化
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}优点:简单,线程安全
缺点:类加载时就创建,可能造成资源浪费
2. 饿汉式(静态代码块)
public class Singleton {
private static final Singleton INSTANCE;
static {
INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}3. 懒汉式(线程不安全)
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}缺点:多线程环境下不安全
4. 懒汉式(同步方法)
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}缺点:每次获取都要同步,效率低
5. 双重检查锁(DCL)
public class Singleton {
// volatile 防止指令重排
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;
}
}推荐:线程安全,延迟加载,效率高
6. 静态内部类
public class Singleton {
private Singleton() {}
// 静态内部类在使用时才加载
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}推荐:利用类加载机制保证线程安全,延迟加载
7. 枚举(最佳实践)
public enum Singleton {
INSTANCE;
public void doSomething() {
System.out.println("Singleton method");
}
}
// 使用
Singleton.INSTANCE.doSomething();最推荐:简洁,线程安全,防止反序列化创建新实例
防止反射攻击
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// 防止反射创建新实例
if (instance != null) {
throw new RuntimeException("Use getInstance() method");
}
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}防止序列化破坏
public class Singleton implements Serializable {
private static final long serialVersionUID = 1L;
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;
}
// 反序列化时调用,返回已有实例
protected Object readResolve() {
return getInstance();
}
}类图
JDK 中的应用
java.lang.Runtime- 饿汉式java.awt.Desktop- 懒汉式
总结
| 实现方式 | 线程安全 | 延迟加载 | 防反射 | 防序列化 |
|---|---|---|---|---|
| 饿汉式 | ✅ | ❌ | ❌ | ❌ |
| 懒汉式(同步) | ✅ | ✅ | ❌ | ❌ |
| 双重检查锁 | ✅ | ✅ | ❌ | ❌ |
| 静态内部类 | ✅ | ✅ | ❌ | ❌ |
| 枚举 | ✅ | ❌ | ✅ | ✅ |
推荐使用枚举或静态内部类实现单例模式。
