设计模式3——单例模式

单例模式是一个比较简单的设计模式,只产生一个具体的对象,一般用于全局变量,保证整个系统所使用的变量是唯一的。

单例模式中,一般将构造函数和析构函数都设置为私有的,获取和释放时采用静态函数实现。

 

具体实例:

SingleInstance.h内容

复制代码
 1 #ifndef SingleInstance_H_H
 2 #define SingleInstance_H_H
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class SingleInstance
 8 {
 9 public:
10     static SingleInstance* getInstance(){
11         if(instance == NULL){
12             instance = new SingleInstance();
13         }
14         return instance;
15     }
16 
17     static void release(){
18         if(instance != NULL){
19             delete instance;
20             instance = NULL;
21         }
22     }
23 
24 private:
25     SingleInstance() {}
26     ~SingleInstance() {}
27     static SingleInstance *instance;
28 };
29 
30 SingleInstance* SingleInstance::instance = NULL;
31 
32 
33 void SingleInstanceTest()
34 {
35     SingleInstance *instance1 = SingleInstance::getInstance();
36     SingleInstance *instance2 = SingleInstance::getInstance();
37     if(instance1 == instance2){
38         cout << "The two instances is the same!" << endl;
39     }
40     else{
41         cout << "The two instances is different!" << endl;
42     }
43     SingleInstance::release();
44 }
45 
46 #endif
复制代码

 由于创建的对象是同一个,因此release()函数调用一次即可。

posted @   丛林小阁楼  阅读(151)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示