设计模式----单例模式 【含实例】

xiaoxiao2025-07-24  26

单例模式,非常常见的一种设计模式。

需求

一个类提供访问该类对象的唯一方式,且全局中有且仅有唯一一个该类的实例。

实现方式

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

 

转载请注明原文地址: https://www.6miu.com/read-5033621.html

最新回复(0)