- // Singleton.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <stdlib.h>
- #include <time.h>
- #include <iostream>
- using namespace std;
- class CSingleton
- {
- private:
- CSingleton(int nIndex)
- {
- this->m_nIndex = nIndex;
- }
- public:
- ~CSingleton()
- {
- }
- public:
- int GetIndex()
- {
- return this->m_nIndex;
- }
- static CSingleton* GetInstance(int nIndex)
- {
- if (NULL == CSingleton::m_pSingle)
- {
- CSingleton::m_pSingle = new CSingleton(nIndex);
- }
- return CSingleton::m_pSingle;
- }
- static void ReleaseInstance()
- {
- if (NULL != CSingleton::m_pSingle)
- {
- delete CSingleton::m_pSingle;
- CSingleton::m_pSingle = NULL;
- }
- }
- private:
- int m_nIndex;
- static CSingleton* m_pSingle;
- };
- //初始化静态成员变量
- CSingleton* CSingleton::m_pSingle = NULL;
- int _tmain(int argc, _TCHAR* argv[])
- {
- CSingleton* pSign = NULL;
- int i = 0;
- int nRand = 0;
- ::srand((unsigned)::time(NULL));
- cout << "测试一" << endl;
- for (i = 0; i < 10; i++)
- {
- nRand = ::rand() % 100;
- pSign = CSingleton::GetInstance(nRand);
- cout << "pSign->nIndex = " << pSign->GetIndex() << "/tnRand = " << nRand << endl;
- }
- //释放内存
- CSingleton::ReleaseInstance();
- cout << "测试二" << endl;
- for (i = 0; i < 10; i++)
- {
- nRand = ::rand() % 100;
- pSign = CSingleton::GetInstance(nRand);
- cout << "pSign->nIndex = " << pSign->GetIndex() << "/tnRand = " << nRand << endl;
- }
- //释放内存
- CSingleton::ReleaseInstance();
- return 0;
- }
Singleton(简单单件模式)C++代码
最新推荐文章于 2025-08-11 09:20:14 发布