C++ 單例模式

#include <iostream>
//單例模式
/*

    C++中的單例模式通常是通過對構造函數設置爲private來實現

*/
using namespace std;

class world
{
    world()
    {
        //私有的構造函數,只能由類的成員函數來獲取實例
    }

public:
    static world *getInstance();
    /*
    static函數也是類函數,所以在寫定義時也要寫明屬於哪個類。與不同類函數不同的是,
    它沒有傳入this指針,正因爲沒有this指針,所以static類成員函數不能訪問非static的
    類成員,只能訪問 static修飾的類成員。
    */
    void show(); //show裏面要用到instance指針,就必須要把實現寫在後面,因爲會要求申明順序
};
static world *instance = nullptr;
world *world::getInstance() //必須在類外實現,否則會提示找不到符號:undefined reference to ...,並且不用加static
{
    if (instance == nullptr)
    {
        instance = new world;
    }
    return instance;
}
void world::show()
{
    cout << "ptr:" << hex <<instance << endl;
}
int main()
{
    world *a = world::getInstance(); //使用類中的static來獲取單個實例
    world *b = world::getInstance(); //雖然是兩個world對象,但是最終只會有一個world實例被創造出來
    a->show();
    b->show();
    //運行程序,就會看到即使我運行了兩次getInstance,實際上的對象只生成了一份
}

 

方法2:

class D{
    private:
        D(){cout<<"D has created!"<<endl;}                   //首先,構造函數設置爲private
    public:
        static D& init(){       //然後
            static D obj_only_1;
            return obj_only_1;
        }
    };
    D obj1=D::init();
    D obj2=D::init();
    D obj3=D::init();   //在這裏可以看到,即使我申請了3個D對象,調用了3次init函數,但是隻會調用一次D的構造函數,即:只輸出一條“D has created!”
    //這就是大名鼎鼎的單例模式
    return 0;

 

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