1. 程式人生 > >C++:利用靜態成員實現“單例模式”

C++:利用靜態成員實現“單例模式”

在網上看了兩三天的網課,瞭解了一下C++,正好做作業遇到一個問題,解決之後覺得有必要寫到部落格裡,就發出來了。
問題是:如何實現“單例模式”,也就是說某個物件只能有一個例項。

思路:
1.需要一個計數器記錄例項的數量,每次成功執行建構函式後計數器自增。計數器為靜態成員。
2.每次呼叫建構函式時先檢查計數器的值是否小於1,小於1則執行建構函式,反之則delete掉這個物件
3.delete掉這個物件的方法就是 delete this; 這個語句就行了
但是這樣就存在一個問題,物件被釋放掉了,可是按照這個思路時無法返回一個被釋放掉的結果,那麼在程式執行中就會存在呼叫不存在的物件的成員函式的情況發生。

解決思路:
1.宣告一個靜態指標成員,型別為該物件的型別,賦初值為NULL。
2.將建構函式的可訪問性設定為—protected。
3.宣告一個返回值為物件指標的靜態函式,在內部寫入if語句,如果計數器小於1,則呼叫建構函式new一個例項並賦值給靜態指標成員並返回該成員,反之直接返回.
這樣就沒有什麼問題了,由於在第二次嘗試例項化物件的時候建構函式並沒有執行,所以不存在記憶體洩漏的現象

注意:由於建構函式不能被直接訪問,所以構造例項時需要用“類名::函式名()”來呼叫,具體請看主函式程式碼。

程式碼如下:

物件宣告標頭檔案:

#pragma once
#include <iostream>
class People { protected: static int num; static People* people; int id; People(int id); public: static People* getObject(int id); int getId(); static int getNum(); };

物件實現檔案:

#include "People.h"

int People::num = 0;
People* People::people = NULL
; People* People::getObject(int id) { if (num < 1) { people = new People(id); } return people; } People::People(int id) { this->id = id; num++; } int People::getId() { return id; } int People::getNum() { return num; }

主函式:

#include <iostream>
#include <Windows.h>
#include "People.h"

using std::cout;
using std::endl;

int main()
{
    People *p1 = People::getObject(1);
    cout << "物件指標p1所指的物件的id = " << p1->getId() << "此時物件的例項數num = " << People::getNum() << endl << endl;

    People *p2 = People::getObject(2);
    cout << "物件指標p2所指的物件的id = " << p1->getId() << "此時物件的例項數num = " << People::getNum() << endl << endl;

    People *p3 = People::getObject(3);
    cout << "物件指標p3所指的物件的id = " << p1->getId() << "此時物件的例項數num = " << People::getNum() << endl << endl;

    People *p4 = People::getObject(4);
    cout << "物件指標p4所指的物件的id = " << p1->getId() << "此時物件的例項數num = " << People::getNum() << endl << endl;

    People *p5 = People::getObject(5);
    cout << "物件指標p5所指的物件的id = " << p1->getId() << "此時物件的例項數num = " << People::getNum() << endl << endl;

    People *p6 = People::getObject(6);
    cout << "物件指標p6所指的物件的id = " << p1->getId() << "此時物件的例項數num = " << People::getNum() << endl << endl;

    system("pause");
}

執行結果:
這裡寫圖片描述