在写 MANET Simulator 时,为了记录 trace 文件,我用了一个 LogFile 的类,这个类为了使用简便,而不必在每个使用日志的类中都建立一个LogFile对象,最好的办法就是把这个LogFile类设计成 Singleton.
具体如下:
1)--------------------------------------- 头文件:
#ifndef _LOG_H_
#define _LOG_H_
#include <iostream>
#include <fstream>
class LogFile
{
private:
LogFile();
~LogFile();
LogFile( const LogFile& ); // Prevent copy-construction.
public:
static LogFile* instance();
private:
static LogFile* pObjLog;
void CloseFiles();
public:
// 1 Error log file, record the errors and warnings.
static std::ofstream m_ofErrLog;
// 2 Running log file, record the running results and hints.
static std::ofstream m_ofRunLog;
// 3 Forwarding log file, record the forwarding actions.
static std::ofstream m_ofForwardLog;
// 4 Location log file, record the nodes' moving actions and locations.
static std::ofstream m_ofLocLog;
// 5 MN's SIR_state log file, record the MN' SIR states.
static std::ofstream m_ofSIRLog;
// 6 Record the Percolation Probability of all MNs.
static std::ofstream m_ofPPLog;
};
#endif
2)--------------------------------------- cpp文件:
#include "..\Log\Log.h"
std::ofstream LogFile::m_ofErrLog("NS_ErrLog.txt");
std::ofstream LogFile::m_ofRunLog("NS_RunLog.txt");
std::ofstream LogFile::m_ofForwardLog("NS_ForwardingLog.txt");
std::ofstream LogFile::m_ofLocLog("NS_LocationLog.txt");
std::ofstream LogFile::m_ofSIRLog("NS_SIRLog.txt");
std::ofstream LogFile::m_ofPPLog( "Trace\\PercoPr.tr", std::ios::app );
LogFile* LogFile::pObjLog = new LogFile();
LogFile::LogFile()
{
}
LogFile::~LogFile()
{
CloseFiles();
if ( NULL != pObjLog )
{
delete pObjLog;
pObjLog = NULL;
}
}
LogFile* LogFile::instance()
{
if ( NULL != pObjLog )
{
return pObjLog;
}
return NULL;
}
void LogFile::CloseFiles()
{
m_ofErrLog.close();
m_ofRunLog.close();
m_ofForwardLog.close();
m_ofLocLog.close();
m_ofSIRLog.close();
m_ofPPLog.close();
}
这样,只要包含了头文件,就可以在其他地方使用静态trace文件记录trace信息了,如:
LogFile::instance()->m_ofErrLog << "Error: the simulate time can not be negative.\n";
或 LogFile::instance()->m_ofRunLog << "\n ----------- The NS begins running now. ----------\n";
整理至此,以便备忘。
Davy 2012_03_15_21:10
本文介绍了一种在MANETSimulator中使用Singleton设计模式来创建LogFile类,以简化日志记录过程并避免重复实例化。通过静态成员变量实现日志文件的共享,使得在不同部分调用日志记录功能时,无需多次创建LogFile对象。举例展示了如何在程序中使用此设计模式进行错误日志、运行日志等记录。
5938

被折叠的 条评论
为什么被折叠?



