设计模式之单例模式(SingletonPattern)

本文详细介绍了单例模式的概念及其在多线程环境下的实现方式,包括如何使用互斥锁和双重检查锁定来确保线程安全。通过实例代码演示了如何创建、获取和释放单例对象,并展示了其在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例类 

系统中一个类只有一个实例,如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

说明:考虑多线程情况需要在代码中加锁;如果线程很多的时候,会有大量线程阻塞可以使用双重锁定。

单例类比较简单直接用代码表示。

//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;
}

运行结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值