单例设计模式

单例设计模式(Singleton Design Pattern)是一种创建型设计模式,其核心目标是确保一个类只有一个实例,并提供一个全局访问点来获取该实例。这种模式适用于需要全局唯一对象的场景,例如配置管理、日志记录、线程池、数据库连接池等

核心思想

  1. 私有化构造函数:防止外部通过 new 关键字直接创建实例。
  2. 静态实例:在类内部维护一个静态的实例。
  3. 全局访问点:通过静态方法(如 getInstance())提供对唯一实例的访问。

实现方式

根据实例化的时机和线程安全的处理方式,单例模式有多种实现方法:

1. 饿汉式(Eager Initialization)

  • 特点:类加载时就初始化实例。
  • 优点:线程安全,实现简单。
  • 缺点:可能造成资源浪费(实例未被使用时也占用内存)
1
2
3
4
5
6
7
8
9
public class Singleton {
private static final Singleton instance = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return instance;
}
}

2. 懒汉式(Lazy Initialization)

  • 特点:延迟实例化,首次调用 getInstance() 时创建实例。
  • 缺点:线程不安全(多线程环境下可能创建多个实例)。
1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton {
private static Singleton instance;

private Singleton() {}

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

3.静态内部类(Static Inner Class)

  • 特点:利用类加载机制保证线程安全,延迟加载。
  • 优点:无需同步,性能高。
1
2
3
4
5
6
7
8
9
10
11
public class Singleton {
private Singleton() {}

private static class Holder {
private static final Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return Holder.instance;
}
}

枚举(Enum)

1
2
3
public enum Singleton {
INSTANCE;
}