64,652
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include "Singleton.h"
using namespace std;
class CMango
{
public:
CMango()
{
cout << "CMango Constructor(). \n" << endl;
}
};
int main()
{
CMango* m1 = CSingleton<CMango>::Instance();
CMango* m2 = CSingleton<CMango>::Instance();
cout << m1 << "\n" << m2 << endl;
return 0;
}
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
// Singleton 模式
#include "sync.h"
// #define NULL ((void *)0)
template <typename T>
class CSingleton
{
private:
CSingleton() {};
static T* _instance;
public:
static T* Instance()
{
// double-check locking
if (_instance == NULL)
{
static CSyncCriSec sync;
sync.Lock();
if (_instance == NULL)
{
_instance = new T();
}
sync.Unlock();
}
return _instance;
}
};
template <typename T>
T* CSingleton<T>::_instance = NULL;
#endif // #ifndef _SINGLETON_H_