设计模式 - 单例模式
封面图
•
2025-11-07
•
设计模式
0
0
0
0
单例模式(Singleton Pattern)是 **创建型设计模式** 中最常见的一种,用于确保一个类只有一个实例,并提供一个全局访问点。 --- ## 🧩 一、定义 > 确保一个类只有一个实例,并提供一个全局访问该实例的接口。 --- ## ✅ 二、适用场景 - 需要频繁实例化然后销毁的对象(如数据库连接、线程池等) - 工具类(如配置管理、日志记录器) - 资源共享对象(如系统全局设置) --- ## 🔧 三、实现方式(Java 示例) ### 1. **懒汉式(线程不安全)** ```java public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ``` ⚠️ **缺点**:多线程环境下可能创建多个实例。 --- ### 2. **懒汉式(线程安全)** ```java public class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ``` ✅ **优点**:线程安全 ❌ **缺点**:每次调用 `getInstance()` 都需要加锁,性能较低 --- ### 3. **饿汉式** ```java public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } } ``` ✅ **优点**:线程安全,简单 ❌ **缺点**:提前加载,可能浪费资源 --- ### 4. **双重检查锁定(Double-Checked Locking)** ```java 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; } } ``` ✅ **优点**:线程安全,延迟加载,性能好 ⚠️ 注意:`volatile` 关键字不能省略,否则可能导致指令重排问题 --- ### 5. **静态内部类(推荐)** ```java public class Singleton { private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } ``` ✅ **优点**:延迟加载 + 线程安全 + 无锁 💡 最推荐的方式! --- ## 🔄 四、单例模式的优缺点 | 优点 | 缺点 | |------|------| | 保证全局唯一实例 | 不容易扩展为多个实例 | | 提高性能(避免重复创建对象) | 可能导致耦合度高 | | 全局访问方便 | 单例对象生命周期长,可能占用资源 | --- ## 📚 五、其他语言中的实现 - **C++**:使用静态成员变量和私有构造函数 - **Python**:通过 `__new__` 方法控制实例创建 - **C#**:使用 `sealed` 类 + `private` 构造函数 + `static` 实例 --- ## 🧠 六、总结 单例模式适用于需要全局唯一实例的场景,但应谨慎使用,避免滥用。推荐使用“静态内部类”方式实现,兼顾线程安全和延迟加载。 --- 如果你需要我为你提供其他语言(如 Python、C++、C#)的单例模式实现,也可以告诉我!
上一篇:
设计模式 - 抽象工厂模式
下一篇:
设计模式 - 建造者模式
标题录入,一次不能超过6条
留言
评论