总所周知,单类模式,就是想让类的对象在程序里是唯一的。就只有一个实例。避免数据丢失等一些作用。
但是,一直以为在整个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