The instance of singleton in application of Tracing-Files

来源:互联网 发布:csgo手机菠菜软件 编辑:程序博客网 时间:2024/04/29 16:00

      在写 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


原创粉丝点击