单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。下面是我的c++实现代码
Singleton.h
#pragma once
#include <afxmt.h>
class CSingleton{
private:
CSingleton();
~CSingleton();
//把拷贝函数和复制函数私有化,防止被复制
CSingleton(const CSingleton&);
CSingleton& operator=(const CSingleton&);
static CSingleton* pInstance;
public:
static CSingleton* getInstance();
// other methods...
};
Singleton.cpp
#include "stdafx.h"
#include"Singleton.h"
static CCriticalSection mMutex;
//私有静态成员变量在使用前必须初始化
CSingleton* CSingleton::pInstance = NULL;
CSingleton::CSingleton(){
}
CSingleton::~CSingleton(){
delete pInstance;
pInstance = NULL;
}
CSingleton::CSingleton(const CSingleton&)
{
}
CSingleton& CSingleton::operator=(const CSingleton&)
{
return *this;
}
CSingleton* CSingleton::getInstance(){
if(pInstance == NULL){
mMutex.Lock(); //多线程下保证对象唯一
if (pInstance==NULL)
{
pInstance = new CSingleton;
}
mMutex.Unlock();
}
return pInstance;
}
main.cpp
#include "stdafx.h"
#include "Singleton.h"
#include <iostream>
#include<process.h>
using namespace std;
unsigned int __stdcall ThreadFunc1(void* param)
{
CSingleton* pObject = (CSingleton*)param;
cout<<pObject->a<<endl;
pObject->a++;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
CSingleton* pSingLenton1 = CSingleton::getInstance();
CSingleton* pSingLenton2 = CSingleton::getInstance();
CSingleton* pSingLenton3 = CSingleton::getInstance();
if (pSingLenton1==pSingLenton2)
{
cout <<"pSingLenton1==pSingLenton2"<<endl;
}
else
{
cout <<"pSingLenton1!=pSingLenton2"<<endl;
}
HANDLE hSaveThread1 =(HANDLE)_beginthreadex(0,0,ThreadFunc1,pSingLenton1,0,0);
Sleep(1000); //保证线程运行的顺序
HANDLE hSaveThread2 =(HANDLE)_beginthreadex(0,0,ThreadFunc1,pSingLenton2,0,0);
Sleep(1000);
HANDLE hSaveThread3 =(HANDLE)_beginthreadex(0,0,ThreadFunc1,pSingLenton3,0,0);
Sleep(5000); //让子线程执行完
return 0;
}