单例类
系统中一个类只有一个实例,如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
说明:考虑多线程情况需要在代码中加锁;如果线程很多的时候,会有大量线程阻塞可以使用双重锁定。
单例类比较简单直接用代码表示。
//Singletion.h
#pragma once
#include <string>
#include <windows.h>
class CSingleton
{
public:
static CSingleton* GetInstance();
static void ReleaseInstance();
void ShowSingletonInfo();
void SetSingletonInfo(std::string strInfo);
private:
CSingleton();
~CSingleton();
//把复制构造函数和=操作符也设为私有,防止被复制
CSingleton(const CSingleton&);
CSingleton& operator=(const CSingleton&);
static CSingleton* m_pSingletion;
static HANDLE m_hMutex;
std::string m_strInfo;
};
//Singleton.cpp
#include "stdafx.h"
#include "Singleton.h"
#include <iostream>
CSingleton* CSingleton::m_pSingletion = NULL;
HANDLE CSingleton::m_hMutex = CreateMutex(NULL, FALSE, NULL);
CSingleton::CSingleton()
{
std::cout << "CSingleton::CSingleton()" << std::endl;
}
CSingleton::~CSingleton()
{
if (NULL == m_pSingletion)
{
std::cout << "CSingleton::~CSingleton(). m_pSingleton is NULL" << std::endl;
}
else
{
std::cout << "CSingleton::~CSingleton(). m_pSingleton is not NULL" << std::endl;
}
std::cout << std::endl;
}
CSingleton* CSingleton::GetInstance()
{
//因为每次判断是否为空都需要被锁定,如果有很多线程的话,就爱会造成大量线程的阻塞,这里采用双向锁定。
if (NULL == m_pSingletion)
{
WaitForSingleObject(m_hMutex, INFINITE);
if (NULL == m_pSingletion)
{
m_pSingletion = new CSingleton;
}
ReleaseMutex(m_hMutex);
}
return m_pSingletion;
}
void CSingleton::ReleaseInstance()
{
WaitForSingleObject(m_hMutex, INFINITE);
if (NULL != m_pSingletion)
{
delete m_pSingletion;
m_pSingletion = NULL;
}
ReleaseMutex(m_hMutex);
}
void CSingleton::ShowSingletonInfo()
{
char msgBuffer[100];
sprintf_s(msgBuffer, 100, "SingletonInfo... ...(%s)", m_strInfo.c_str());
std::cout << msgBuffer << std::endl;
}
void CSingleton::SetSingletonInfo(std::string strInfo)
{
m_strInfo = strInfo;
}
#include "stdafx.h"
#include "Singleton.h"
int _tmain(int argc, _TCHAR* argv[])
{
CSingleton* p1 = CSingleton::GetInstance();
p1->SetSingletonInfo("11");
p1->ShowSingletonInfo();
p1->ReleaseInstance();
CSingleton* p2 = CSingleton::GetInstance();
p2->SetSingletonInfo("22");
p2->ShowSingletonInfo();
CSingleton* p3 = CSingleton::GetInstance();
p3->ShowSingletonInfo();
p3->ReleaseInstance();
return 0;
}
运行结果: