【C++】设计模式全解析——单例模式(code c++)


单例模式

保证一个类仅有一个实例,并提供一个访问它的全局访问点

  • 主要解决:一个全局使用的类频繁地创建与销毁;
  • 何时使用: 想控制实例数目,节省系统资源的时候;
  • 如何解决: 判断系统是否已存在单例,如果有则返回,没有则创建;
  • 关键代码: 默认构造私有,拷贝构造私有(注意 delete)

单例的实现主要有两种:懒汉式和饿汉式

  • 懒汉: 故名思义,不到万不得已就不会去实例化类,也就是说在第一次用到类实例的时候才会去实例化
  • 饿汉: 饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化

特点与选择:

  • 在访问量较小时,采用懒汉实现。实现复杂,要保证线程安全。这是以时间换空间
  • 由于要进行线程同步,所以在访问量比较大,或者访问的线程比较多时,采用饿汉实现,可以实现更好的性能。这是以空间换时间

程序代码

懒汉式实现:加 lock,线程安全 code c++

#include <iostream>
#include <mutex>
using namespace std;

class Singleton {
public :
    static Singleton *getSingleton(); // 类方法, 1 可访问类私有成员, 2 不依赖对象
private:
    Singleton() {} // 默认构造私有化
    Singleton (const Singleton &) = delete; // 拷贝构造删除
    Singleton &operator=(const Singleton &) = delete; // 复制操作删除
    static Singleton *single;
    static mutex mut;
};

Singleton *Singleton::getSingleton() {
    if (single == nullptr) { // 线程安全下的效率
        unique_lock<mutex> lock(mut); // 多线程, 线程安全
        if (single == nullptr) { 
            single = new Singleton();
        }
    }
    return single;
}

Singleton *Singleton::single = nullptr; // 懒汉模式 加锁线程安全
mutex Singleton::mut;

int main() { // 单例模式使用场景, 资源控制
    Singleton *s1 = Singleton::getSingleton(); 
    return 0;
}

饿汉式实现:线程安全 code c++

#include <iostream>
using namespace std;

class Singleton {
public :
    static Singleton *getSingleton(); // 类方法, 1 可访问类私有成员, 2 不依赖对象
    int getCnt();
private:
    Singleton() {} // 默认构造私有化
    Singleton(const Singleton &) = delete; // 拷贝构造删除
    Singleton &operator=(const Singleton &) = delete; // 复制操作删除
    static Singleton *single;
    static int cnt;
};

Singleton *Singleton::getSingleton() {
    if (single == nullptr) {
        single = new Singleton();
        ++cnt;
    }
    return single;
}
int Singleton::getCnt() {
    return cnt;
}
Singleton *Singleton::single = Singleton::getSingleton(); // 饿汉模式 主线程静态初始化 single 线程安全
int Singleton::cnt = 0;

int main() { // 单例模式使用场景, 资源控制
    Singleton *s1 = Singleton::getSingleton();
    Singleton *s2 = Singleton::getSingleton();
    Singleton *s3 = Singleton::getSingleton();
    cout << s3->getCnt() << endl;
    return 0;
}

结论

代码示例,有问题留言。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

idiot5liev

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值