设计模式之单例模式



#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;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章