設計模式----單例模式 【含例項】
阿新 • • 發佈:2018-11-07
單例模式,非常常見的一種設計模式。
需求
一個類提供訪問該類物件的唯一方式,且全域性中有且僅有唯一一個該類的例項。
實現方式
1.建構函式private,類外不可建立類例項
2.提供訪問類例項的介面getInstance
3.建立static private的類物件
程式碼
//main.h #ifndef MAIN_H #define MAIN_H #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> class MyObject { public: static MyObject* getInstance(); ~MyObject(){std::cout<<"~MyObject()"<<std::endl;} private: static MyObject* g_myObject; MyObject(){} // GC 機制 class GC { public: ~GC() { if (g_myObject != NULL) { std::cout<<"Here destroy the g_myObject..." << std::endl; delete g_myObject; g_myObject = NULL; } } static GC gc; // 用於釋放單例 }; }; #endif // MAIN_H
#include "main.h" #include "unistd.h" MyObject::GC MyObject::GC::gc; // 重要 MyObject* MyObject::g_myObject = NULL; MyObject* MyObject::getInstance(){ if(NULL == g_myObject) { g_myObject = new MyObject(); } return g_myObject; } int main(int argc, char *argv[]) { printf("========hello======\n"); MyObject * obj = MyObject::getInstance(); sleep(5); printf("-------exit--------\n"); return 0; }
輸出結果
Starting /home/user/build-TestList-Desktop_Qt_5_9_5_GCC_64bit-Debug/TestList...
========hello======
-------exit--------
Here destroy the g_myObject...
~MyObject()
/home/user/build-TestList-Desktop_Qt_5_9_5_GCC_64bit-Debug/TestList exited with code 0
總結
學習中發現了博主寫的釋放資源時採用gc機制,很受用。
可以看出如果刪去GC類的程式碼部分,程式退出時,static物件指標指向的物件不會被析構,即系統不會自動去呼叫MyObject的解構函式去釋放g_myObject指向的物件。
例如:
class A{
};
static A a;//會析構
static A* a = new A();//不會被析構
但是程式碼中的static GC gc;在程式結束時會呼叫gc的解構函式,同時delete g_myObject。
參考大神部落格https://blog.csdn.net/liang19890820/article/details/61615495#commentsedit