1. 程式人生 > 其它 >[C++][設計模式] 單例設計模式

[C++][設計模式] 單例設計模式

技術標籤:C++設計模式c++設計模式

效果:

  • 記憶體中只能有一份物件,即類在記憶體中只能有1個例項(通過該類只能建立一個物件)

實現步驟:

  1. 將建構函式私有化。
  2. 在類中定義一個靜態的指標變數(一般設為私有),並在類外初始化為空
  3. 定義一個返回值為類指標的靜態成員函式,如果2中的指標物件為空,則初始化物件,以後再有物件呼叫該靜態成員函式的時候,不再初始化物件,而是直接返回物件,保證類在記憶體中只有一個例項。

解釋:

  • 建構函式私有化是為了保證除了自己定義的類的靜態方法(此文章中的static Singleton * getInstance()),其他方式均不能構造類的例項,間接保證類在記憶體中只有一個例項。

程式碼:

#include <iostream>

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

class Singleton
{
public:
    static Singleton * getInstance()
    {
        if(nullptr==_pInstance)  //若指標物件為空,則初始化物件
        {
            _pInstance=new Singleton();
        }
        return _pInstance;
    }

    static void destory
() { if(_pInstance) { delete _pInstance; } } void print() { cout << "data= " << _data << endl; } private: Singleton() //建構函式私有化 : _data(0) { cout << "Singleton()" <<
endl; } ~Singleton() { cout << "~Singleton()" << endl; } private: int _data; static Singleton *_pInstance; //靜態指標變數 }; Singleton *Singleton::_pInstance=nullptr; //類外初始化靜態指標變數 int main() //測試 { Singleton *p1=Singleton::getInstance(); Singleton *p2=Singleton::getInstance(); cout<<"p1= "<<p1<<endl <<"p2= "<<p2<<endl; Singleton::destory(); return 0; }

結果:
在這裡插入圖片描述
分析:

  • 指標p1跟p2指向的記憶體空間地址相同,即整個記憶體中類的例項只有一個。

2021/1/13