本实例是用静态类实现singleton单例模式

/*=================================================================
 *注意:
 *     在接口与数据的安排上,是先接口后数据,这样体现了以行为为中心
 *     但是有一个前提就是,无论如何先将构造函数和析构函数摆在最前面
 *     因为构造函数和析构函数首先决定了这个类的性质,比如说,
 *     带虚析构函数的一般是用来做基类,构造函数不是public的,说明设计师
 *     不想实例化该类
 *一般的结构为:
 *     构造函数
 *     析构函数
 *     public函数
 *     protected函数
 *     private函数
 *     public变量
 *     protectd变量
 *     private变量
 *
 *     本实例是用静态类实现singleton单例模式
 *=================================================================*/

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

class Logger
{
  private:
    Logger(){}

  public:
    //logs a single message at the given log level
    static void log(const string& strMessage, const string& strLogLevel);

    //logs a vector of messages at the given log level
    static void log(const vector<string>& strMessages, const string& strLogLevel);

    //Closes the log file
    static void teardown(void);

  protected:
    static void init(void);

  public:
    static const string m_strLogLevelDebug;
    static const string m_strLogLevelInfo;
    static const string m_strLogLevelError;

  protected:
    static const char* const m_szLogFileName;
    static bool sInitialized;
    static ofstream sOutputStream;

}

#include "logger.h"
using namespace std;

const string Logger::m_strLogLevelDebug = "DEBUG";
const string Logger::m_strLogLevelInfo = "INFO";
const string Logger::m_strLogLevelError = "ERROR";

const char* const Logger::m_szLogFileName = "log.out";
bool Logger::sInitialized = false;
ofstream Logger::sOutputStream;

void Logger::log(const string& strMessage,const string& strLogLevel)
{
  if(!sInitialized)
  {
     init();
  }

  sOutputStream << strLogLevel<<":"<<strMessage<<endl;
}

void Logger::log(const vector<string>& strMessages,const string& strLogLevel)
{
   for(size_t i = 0; i < strMessages.size(); ++i)
   {
     log(strMessages[i],strLogLevel);
   }
}

void Logger::teardown(void)
{
    if(sInitialized)
    {
       sOutputStream.close();
       sInitialized = false;
    }
}

void Logger::init(void)
{
    if( !sInitialized )
    {
        sOutputStream.open(szLogFileName,ios_base::app);

        if( !sOutputStream.good() )
        {
            cerr<<"Unable to initialize the logger"<<endl;
            return;
        }
        sInitialized = true;
    }
}

int main(int argc, char** argv)
{
   Logger::log("test message", Logger::kLogLevelDebug);

   vector<string> items;
   items.push_back("item1");
   items.push_back("item2");

   Logger::log(items, Logger::kLogLevelError);

   Logger::teardown();
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值