如何在 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

更新於:30-07-2019

1K+ 瀏覽數

開啟你的 職業生涯

完成本課程並獲得認證

開始學習
廣告