Singleton 设计模式是一种常用的软件设计模式,用于确保一个类只有一个实例,并提供一个全局访问点来获取这个实例。
核心概念
- 单例类:只能创建一个实例的类。
- 全局访问点:外部获取单例实例的接口。
实现方式
饿汉式
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
懒汉式
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
双重校验锁
public class Singleton {
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;
}
}
应用场景
- 资源管理:如数据库连接池、文件操作等。
- 配置信息管理:如系统配置、用户配置等。
- 工具类:如日志工具类、缓存工具类等。
扩展阅读
Singleton Pattern