单类模式一点新认识-析构及作用域

总所周知,单类模式,就是想让类的对象在程序里是唯一的。就只有一个实例。避免数据丢失等一些作用。

但是,一直以为在整个solution里是唯一的。其实不然,只能保证在每个project里是唯一实例。


前段时间写个记录error的单类,想在engine这层用,有想在底层库里也调用。本想把error都写到同一个error log实例中,其实他们各自产生了一个对象。

因此,推断,所谓只有一个实例,只是局限在模块内。


第二个问题,我想通常容易忽视的,因为单类模式的 构造和析构都是private的。

然后,我们可以getinstance 一个实例,却总是忘掉release他们。

因此,还是要写releaseinstance的方法的。

/************************************************************************/
/*  Name: MyLog.h
* Function: record consume time
* Author: liyy
* Date: 2013.04.27
*/
/************************************************************************/
#ifndef _MYLOG_H
#define _MYLOG_H

#pragma once
#include <string>

class CMyLog
{
public:
protected:
	CMyLog(void);
	int OpenFile();
	CMyLog(std::string filePath);
	~CMyLog(void);


public:
	static CMyLog * GetInstance(std::string filePath)
{
	if (CMyLog::m_log == NULL)
	{
		CMyLog::m_log = new CMyLog(filePath);
		//CMyLog::m_log->OpenFile()
		//CMyLog::m_log->m_filePath = this.m_filePath;
	}
	return CMyLog::m_log;

};
	static void  ReleaseInstance(std::string filePath)
	{
		if (m_log->GetInstance(filePath) != NULL)
		{
			delete m_log->GetInstance(filePath);
			m_log = NULL;
		}
	};

int WriteLog(std::string strSentenc);
//int CloseFile();
std::string Doulbe2String(double dValue,int decplace = 3);

private:
	std::string m_filePath;
	static CMyLog *m_log;

};
#endif


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值