单例模式看起来也蛮简单的,就是在系统中只允许产生这个类的一个实例,既然这么简单,就直接贴代码了。更详细的内容及说明可以参考原作者博客:cbf4life.cnblogs.com。
3.1.解释
main(),大臣
CEmperor,需要单例的类
说明:很多大臣拜见的皇帝,只有一个。体现在面向对象方面,CEmperor定义一个静态指针,和一个静态函数,私有化构造函数、析构函数、构造函数复制、重载赋值语句。
注意:线程安全,采用互斥体的方式实现。
看代码:
//Emperor.h
#pragma once
#include <iostream>
using std::cout;
using std::endl;
using std::string;
class CEmperor
{
public:
static CEmperor * GetInstance();
static void ReleaseInstance();
void EmperorInfo(void);
void SetEmperorTag(string tag);
private:
CEmperor(void);
virtual ~CEmperor(void);
CEmperor(const CEmperor&);
CEmperor& operator=(const CEmperor&);
static CEmperor *m_pEmperor;
static HANDLE m_pMutex;
string m_EmperorTag;
class CGarbo
{
public:
CGarbo()
{
cout << "Create Garbo" << endl;
}
~CGarbo()
{
cout << "Destroy Garbo" << endl;
if (NULL != m_pEmperor)
{
WaitForSingleObject(m_pMutex, INFINITE);
if (NULL != m_pEmperor)
{
cout << "Remove instance" << endl;
delete m_pEmperor;
m_pEmperor = NULL;
}
ReleaseMutex(m_pMutex);
}
if (NULL != m_pMutex)
{
cout << "Delete mutex" << endl;
CloseHandle(m_pMutex);
m_pMutex = NULL;
}
}
};
static CGarbo m_Garbo;
};
//Emperor.cpp
#include "StdAfx.h"
#include "Emperor.h"
#include <iostream>
using std::cout;
using std::endl;
using std::string;
CEmperor* CEmperor::m_pEmperor = NULL;
HANDLE CEmperor::m_pMutex = CreateMutex(NULL, FALSE, NULL);
CEmperor::CGarbo CEmperor::m_Garbo;
CEmperor::CEmperor(void)
{
cout << "Create CEmperor Instance" << endl;
}
CEmperor::~CEmperor(void)
{
cout << "Destroy CEmperor Instance and release its resource" << endl;
}
void CEmperor::EmperorInfo(void)
{
char msgBuffer[50] = { 0 };
sprintf_s(msgBuffer, 50, "皇ê帝?某3某3某3... ...(%s).", m_EmperorTag.c_str());
string msg(msgBuffer);
cout << msg.c_str() << endl;
}
CEmperor* CEmperor::GetInstance()
{
if (NULL == m_pEmperor)
{
WaitForSingleObject(m_pMutex, INFINITE);
if (NULL == m_pEmperor)
m_pEmperor = new CEmperor();
ReleaseMutex(m_pMutex);
}
return m_pEmperor;
}
void CEmperor::ReleaseInstance()
{
if (NULL != m_pEmperor)
{
WaitForSingleObject(m_pMutex, INFINITE);
if (NULL != m_pEmperor)
{
delete m_pEmperor;
m_pEmperor = NULL;
}
ReleaseMutex(m_pMutex);
}
}
void CEmperor::SetEmperorTag( string tag )
{
m_EmperorTag = tag;
}
//Singleton.cpp
#include "stdafx.h"
#include "Emperor.h"
void DoIt()
{
CEmperor *pEmperor1 = CEmperor::GetInstance();
pEmperor1->SetEmperorTag("95");
pEmperor1->EmperorInfo(); CEmperor *pEmperor2 = CEmperor::GetInstance();
pEmperor2->EmperorInfo(); CEmperor *pEmperor3 = CEmperor::GetInstance();
pEmperor3->EmperorInfo(); CEmperor *pEmperor4 = pEmperor3;
pEmperor4->EmperorInfo(); CEmperor *pEmperor5 = NULL;
pEmperor5 = pEmperor4;
pEmperor5->EmperorInfo(); CEmperor::ReleaseInstance();
}
int _tmain(int argc, _TCHAR* argv[])
{
DoIt();
_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF);
_CrtDumpMemoryLeaks();
return 0;
}
单例模式比较简单,但在项目中使用的时候,需要明确只调用CEmperor的GetInstance函数来获取实例。在C#里
有更简单的方法,那就是声明只读的静态变量,比C++简单多了。
但C++更吸引人们去研究,这就是软件研发的乐趣吧。