设计模式之单例模式



#include<iostream>//懒汉式
using  namespace std;

class Singleton{
private:
    static Singleton *instance;
    Singleton(){};
public:
    static  Singleton * getinstance(){
        if (instance==NULL){
            instance = new Singleton();
        }
        return instance;

    }

};
Singleton * Singleton::instance =NULL;

int main(){
    Singleton *s1 = Singleton::getinstance();
    Singleton *s2 = Singleton::getinstance();

    if(s1 ==s2){
        cout<<"the same"<<endl;
    }

    return 0;
}



#include <iostream>
using namespace std;
//饿汉式
class singleton{
private:
    singleton(){};

public:
    static singleton * getinstance(){
        static singleton instance;
        return & instance;
    }
};

int main(){
    singleton *s1 = singleton::getinstance();
    singleton *s2 = singleton::getinstance();

    if(s1 ==s2){
        cout<<"the same"<<endl;
    }

    return 0;
}

//深入理解懒汉式和饿汉式,看定义的是静态成员变量还是静态成员对象指针变量,
// 因为如果定义了静态成员对象变量,程序在运行之初就分配了空间,就要调用构造函数了
// 在调用 getinstance 时,不会再次调用构造函数了
//相反的话,如果定义的是指针变量的话程序运行之初也会分配空间,但是这个空间是指针的空间,不是对象的空间
//而只有在调用getinstance 进行new 操作的时候才会调用其构造函数





//线程安全下的懒汉模式

class safesingleton{
private:
    safesingleton(){};

    static safesingleton * instance;
public:

    static safesingleton * getinstance(){
        if(instance==NULL){
            lock();
            if(instance==NULL){//在这里要双重确认
                instance = new safesingleton();
            }
        }
        return instance;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值