单例模式

前言

单例模式估计是校招考的最多的了,没想到此刻还在复习单例模式。
单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

代码

单线程时的单例

Singleton.h
懒汉式

#ifndef SINGLETON_H
#define SINGLETON_H

class Singleton {
private:
    static Singleton *instance;
    Singleton() {};
    ~Singleton() = default;
    Singleton(const Singleton &) = delete;
    Singleton &operator=(const Singleton &) = delete;
public:
    static Singleton *getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton *Singleton::instance = nullptr;

#endif //SINGLETON_H

main.cpp

#include <iostream>
#include "Singleton.h"

using namespace std;

int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();
    if (s1 == s2) {
        cout<<"两个对象是相同的实例";
    }
    return 0;
}

多线程时的单例

在C++11内部静态变量的方式里是线程安全的,只创建了一次实例。
Singleton.h

#ifndef SINGLETON_H
#define SINGLETON_H


class Singleton {
private:
    Singleton() {};
    ~Singleton() = default;
    Singleton(const Singleton &) = default;
    Singleton &operator=(const Singleton &) = delete;

public:
    int para{};

    static Singleton &getInstance() {
        static Singleton singleton;
        return singleton;
    }
};
#endif //SINGLETON_H

main.cpp

#include <iostream>
#include "Singleton.h"

using namespace std;

int main() {
    Singleton::getInstance().para = 5;
    cout<<Singleton::getInstance().para<<endl;
    cout<<Singleton::getInstance().para<<endl;
    return 0;
}

参考

C++ 单例模式

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值