Singleton(简单单件模式)C++代码

本文介绍了一个简单的单例模式实现案例,通过C++代码展示了如何创建并使用单例对象。程序通过随机数生成不同索引值来测试单例模式的一致性,并在每次测试结束后释放已分配的内存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. // Singleton.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <stdlib.h>
  5. #include <time.h>
  6. #include <iostream>
  7. using namespace std;
  8. class CSingleton
  9. {
  10. private:
  11.     CSingleton(int nIndex)
  12.     {
  13.         this->m_nIndex = nIndex;
  14.     }
  15. public:
  16.     ~CSingleton()
  17.     {
  18.     }
  19. public:
  20.     int GetIndex()
  21.     {
  22.         return this->m_nIndex;
  23.     }
  24.     static CSingleton* GetInstance(int nIndex)
  25.     {
  26.         if (NULL == CSingleton::m_pSingle)
  27.         {
  28.             CSingleton::m_pSingle = new CSingleton(nIndex);
  29.         }
  30.         return CSingleton::m_pSingle;
  31.     }
  32.     static void ReleaseInstance()
  33.     {
  34.         if (NULL != CSingleton::m_pSingle)
  35.         {
  36.             delete CSingleton::m_pSingle;
  37.             CSingleton::m_pSingle = NULL;
  38.         }
  39.     }
  40.     
  41. private:
  42.     int     m_nIndex;
  43.     static  CSingleton* m_pSingle;
  44. };
  45. //初始化静态成员变量
  46. CSingleton* CSingleton::m_pSingle = NULL;
  47. int _tmain(int argc, _TCHAR* argv[])
  48. {
  49.     CSingleton* pSign = NULL;
  50.     int i       = 0;
  51.     int nRand   = 0;
  52.     ::srand((unsigned)::time(NULL));
  53.     cout << "测试一" << endl;
  54.     for (i = 0; i < 10; i++)
  55.     {
  56.         nRand = ::rand() % 100;
  57.         pSign = CSingleton::GetInstance(nRand);
  58.         cout << "pSign->nIndex = " << pSign->GetIndex() << "/tnRand = " << nRand << endl;
  59.     }
  60.     //释放内存
  61.     CSingleton::ReleaseInstance();
  62.     cout << "测试二" << endl;
  63.     for (i = 0; i < 10; i++)
  64.     {
  65.         nRand = ::rand() % 100;
  66.         pSign = CSingleton::GetInstance(nRand);
  67.         cout << "pSign->nIndex = " << pSign->GetIndex() << "/tnRand = " << nRand << endl;
  68.     }
  69.     //释放内存
  70.     CSingleton::ReleaseInstance();
  71.     
  72.     return 0;
  73. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值