The instance of singleton in application of Tracing-Files

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值