C++ 单例模式

单例模式的声明

头文件:Singletion.h

 
// 单例模式申明
#define PATTERN_SINGLETON_DECLARE(classname)\
public:\
static classname* Instance();\
static void Close();\
private:\
static classname* m_pSingletion;

// 单例模式实现
#define PATTERN_SINGLETON_IMPLEMENT(classname)\
classname* classname::m_pSingletion = NULL;\
	classname* classname::Instance()\
{\
if (m_pSingletion == NULL)\
{\
m_pSingletion = new classname;\
}\
return m_pSingletion;\
}\
void classname::Close()\
{\
if (m_pSingletion != NULL)\
{\
delete m_pSingletion;\
m_pSingletion = NULL;\
}\
}

使用方法

头文件

假设类 sample需要使用单例模式,则在类sample的头文件中声明

#include "Singletion.h"
#define INST_SAMPLE sample::Instance()
class sample
{
	PATTERN_SINGLETON_DECLARE(sample)
public:
	sample();
	~sample();
	//具体的功能 随意
	。。。。。。
}

这样写就相当于是:

#include "Singletion.h"
#define INST_SAMPLE sample::Instance()
class CDSPluginMainUI
{
	public:
	static sample* Instance();
	static void Close();
	private:
	static sample* m_pSingletion;
	
public:
	sample();
	~sample();
}

就是多加了一个 私有成员指针,两个静态函数

.cpp

在实现的cpp中

#include "sample.h"

PATTERN_SINGLETON_IMPLEMENT(sample)
sample::sample()
{

}

相当于是

sample* sample::m_pSingletion = NULL;

sample* sample::Instance()
{
	if (m_pSingletion == NULL)
	{
		m_pSingletion = new sample;
	}
		return m_pSingletion;
}

void sample::Close()
{
	if (m_pSingletion != NULL)
	{
		delete m_pSingletion;
		m_pSingletion = NULL;
	}
}

完成之后 就可以使用函数Instance()
为了使用方便 我们在头文件中定义

#define INST_SAMPLE sample::Instance()
之后就可以用 INST_SAMPLE 调用这个类了

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值