說明 C++ 單例設計模式。
單例設計模式是一種軟體設計原則,用於將類的例項限制為一個物件。當系統中需要一個物件來協調操作時,這非常有用。例如,如果你使用一個記錄器來將日誌寫入檔案,則可以建立單例類來建立這樣的記錄器。你可以使用以下程式碼建立單例類 −
示例
#include <iostream> using namespace std; class Singleton { static Singleton *instance; int data; // Private constructor so that no objects can be created. Singleton() { data = 0; } public: static Singleton *getInstance() { if (!instance) instance = new Singleton; return instance; } int getData() { return this -> data; } void setData(int data) { this -> data = data; } }; //Initialize pointer to zero so that it can be initialized in first call to getInstance Singleton *Singleton::instance = 0; int main(){ Singleton *s = s->getInstance(); cout << s->getData() << endl; s->setData(100); cout << s->getData() << endl; return 0; }
輸出
將給出以下輸出 −
0 100
廣告