癖艺泣 发表于 2025-6-5 19:48:40

单例模式

目录

[*]什么是单例模式?
[*]单例模式的特点
[*]单例模式的实现方式
[*]懒汉模式

[*]实现一(非线程安全)
[*]实现二(线程安全)
[*]实现三(线程安全、推荐)

[*]饿汉模式
[*]总结

什么是单例模式?

单例模式属于简单设计模式的一种。在整个系统的生命周期内,单例类有且只有唯一一个对象,典型的应用比如日志的句柄。使用单例模式时需要考虑线程安全的问题,具体看后文具体的代码解析。
单例模式的特点


[*]单例类只能有一个实例。
[*]成员是私有的、静态的。
[*]禁止拷贝、赋值,构造函数、私有函数是私有的。
单例模式的实现方式


[*]懒汉模式:在需要使用的时候才实例化对象。
[*]饿汉模式:在系统刚启动时就实例化对象。
懒汉模式

实现一(非线程安全)

#include #include #include #include #define MAX_THREAD_SIZE 10class Singleton{public:    static Singleton* GetInstance();    static void DeleteInstance();    void Print(int index);    Singleton(const Singleton& kSingleton) = delete;    Singleton* operator=(const Singleton& kSingleton) = delete;private:    Singleton();    ~Singleton();    static Singleton* singleton_;};Singleton::Singleton(){    std::cout
页: [1]
查看完整版本: 单例模式