设计模式——单例模式

一、单例模式要点

1、构造函数设置为私有函数,不允许类外创建
2、提供静态接口供客户获取单例
3、将类指针设为静态,因为静态函数只能操作静态变量
4、静态类指针类外初始化

二、懒汉模式

  1. 实例创建时机:第一次访问实例的时候创建
  2. 模式类别:线程不安全、线程安全1、线程安全2
//线程不安全之懒汉模式 
class singlelazy {
public:
    static singlelazy* getInstance() {
        if (lazy == nullptr)
            lazy = new singlelazy();
        return lazy;
    }
private:
    singlelazy() {};
    static singlelazy* lazy;
};
singlelazy* singlelazy::lazy = nullptr;

//线程安全之懒汉模式1
mutex mt;
class singlelazy {
public:
    static singlelazy* getInstance() {
        mt.lock();
        if (lazy == nullptr)
            lazy = new singlelazy();
        mt.unlock();
        return lazy;
    }
private:
    singlelazy(){};
    static singlelazy* lazy;
};
singlelazy* singlelazy::lazy = nullptr;

//线程安全之懒汉模式2
mutex mt;
class singlelazy {
public:
    static singlelazy* getInstance() {
        if (lazy == nullptr) {
            mt.lock();
            if (lazy == nullptr)
                lazy = new singlelazy();
            mt.unlock();
        }
        return lazy;
    }
private:
    singlelazy(){};
    static singlelazy* lazy;
};
singlelazy* singlelazy::lazy = nullptr;

三、饿汉模式

  1. 实例创建时机:第一次访问实例的时候创建
  2. 模式类别:线程安全
//饿汉模式
class singlehungry {
public:
    static singlehungry* getInstance() {
        return hungry;
    }
private:
    singlehungry() {};
    static singlehungry* hungry;
};
singlehungry* singlehungry::hungry = new singlehungry();

四、单例模式的调用

int main()
{   //懒汉模式
    singlelazy* lazy1 = singlelazy::getInstance();
    singlelazy* lazy2 = singlelazy::getInstance();
    if (lazy1 == lazy2)
        cout << "singlelazy is single_example" << endl;
    else
        cout<<  "singlelazy is not single_example" << endl;
    //饿汉模式
    singlehungry* hungry1 = singlehungry::getInstance();
    singlehungry* hungry2 = singlehungry::getInstance();
    if(hungry1==hungry2)
        cout<< "singlehungry is single_example" << endl;
    else
        cout << "singlehungry is not single_example" << endl;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值