Java单例模式、懒汉模式、饿汉模式和懒加载
好的!我们来详细讲解单例模式、懒汉模式、饿汉模式和懒加载,争取让你看完就懂!
🟦 一、单例模式(Singleton Pattern)
定义:确保一个类只有一个实例,并提供一个全局访问点。
应用场景:
- 需要共享资源,如数据库连接池、日志对象、配置文件等。
- 限制实例化,节省资源,避免多个实例冲突。
🟦 二、单例模式的实现方式
单例模式主要有懒汉模式和饿汉模式,我们分别讲解。
🔵 1. 饿汉模式(Eager Initialization)
- 特点:类加载时就创建实例,不管是否会用到,线程安全。
- 优点:简单,没有并发问题。
- 缺点:可能造成内存浪费,因为即使不用也会提前创建。
代码示例:
class SingletonEager {
// 类加载时就创建实例
static instance = new SingletonEager();
// 私有化构造函数,防止外部实例化
private constructor() {}
// 提供全局访问点
static getInstance() {
return this.instance;
}
showMessage() {
console.log("饿汉模式:我是唯一的实例!");
}
}
// 使用
const instance1 = SingletonEager.getInstance();
const instance2 = SingletonEager.getInstance();
console.log(instance1 === instance2); // true
🔵 2. 懒汉模式(Lazy Initialization)
- 特点:类加载时不创建实例,第一次调用
getInstance()
时才初始化。 - 优点:节省资源,按需创建,延迟加载。
- 缺点:在多线程环境下需要加锁处理,否则会出现线程安全问题。
代码示例(非线程安全版):
class SingletonLazy {
// 静态变量,初始为 null
static instance = null;
// 私有化构造函数
private constructor() {}
// 延迟初始化
static getInstance() {
if (this.instance === null) {
this.instance = new SingletonLazy();
}
return this.instance;
}
showMessage() {
console.log("懒汉模式:我只会在需要时才初始化!");
}
}
// 使用
const instance1 = SingletonLazy.getInstance();
const instance2 = SingletonLazy.getInstance();
console.log(instance1 === instance2); // true
代码示例(线程安全版):
class SingletonLazySafe {
static instance = null;
private constructor() {}
static getInstance() {
// 双重检查锁定
if (!this.instance) {
// 加锁,防止并发问题
this.instance = new SingletonLazySafe();
}
return this.instance;
}
showMessage() {
console.log("线程安全的懒汉模式!");
}
}
🟦 三、懒加载(Lazy Loading)
定义:按需加载资源,延迟初始化,等到真正需要时再进行加载。
应用场景:
- Vue 的路由懒加载(按需加载组件)。
- 图片懒加载,滚动到可视区域才加载,提升性能。
简单代码示例:
let data = null;
function getData() {
if (!data) {
console.log("数据初始化中...");
data = { name: "懒加载数据", value: 42 };
}
return data;
}
console.log(getData()); // 第一次调用会初始化
console.log(getData()); // 第二次调用直接使用已初始化的数据
🟦 四、总结对比
模式 | 何时实例化 | 线程安全 | 资源开销 | 复杂度 |
---|---|---|---|---|
饿汉模式 | 类加载时 | 是 | 高 | 低 |
懒汉模式(非线程安全) | 第一次调用时 | 否 | 低 | 低 |
懒汉模式(线程安全) | 第一次调用时 | 是 | 低 | 中等 |
懒加载 | 需要时加载 | 取决于实现 | 低 | 低 |
🟦 五、总结归纳
- 单例模式:只允许一个实例,全局访问。
- 懒汉模式:需要时再初始化,按需创建。
- 饿汉模式:类加载时就初始化,预先创建。
- 懒加载:按需加载数据或资源,节省性能开销。