在 Singleton 模式中,通过维护一个 static 的成员变量来记录这个唯一的对象实例。通过提供一个 staitc 的接口 instance 来获得这个唯一的实例。
- /*
- * Logger.h
- */
- #include <iostream>
- #include <fstream>
- #include <vector>
- using namespace std ;
- class Logger {
- public:
- static const string kLogLevelDebug ;
- static const string kLogLevelInfo ;
- static const string kLogLeveleError ;
- //Log a single message
- /* static void log( const string& inMessage , */
- /* const string& inLogLevel ) ; */
- /* static void log( const vector<string>& inMessage , */
- /* const string& inLogLevel ) ; */
- // static void teardown() ;
- void log( const string& inMessage ,
- const string& inLogLevel ) ;
- void log( const vector<string>& inMessage ,
- const string& inLogLevel ) ;
- //return a reference to the singleton object
- static Logger& instance() ;
- protected:
- //static void init() ;
- //static bool isInited ;
- static Logger sInstance ;
- static const char* const kLogFileName ;
- //Data member for the output stream
- ofstream sOutputStream ;
- private:
- Logger() ;
- ~Logger() ;
- } ;
- /*
- * Logger.cpp
- */
- #include <string>
- #include "Logger.h"
- using namespace std ;
- const string Logger::kLogLevelDebug = "DEBUG" ;
- const string Logger::kLogLevelInfo = "INFO" ;
- const string Logger::kLogLeveleError = "ERROR" ;
- const char* const Logger::kLogFileName = "log.out" ;
- Logger Logger::sInstance ;
- void Logger::log( const string& inMessage ,
- const string& inLogLevel ) {
- // if ( !isInited ) {
- // init() ;
- // }
- sOutputStream << inLogLevel << " " << inMessage << endl ;
- }
- void Logger::log( const vector<string>& inMessage ,
- const string& inLogLevel ){
- for ( size_t i = 0 ; i < inMessage.size() ; i ) {
- log( inMessage[i] , inLogLevel ) ;
- }
- }
- // void Logger::teardown() {
- // if (isInited ) {
- // sOutputStream.close() ;
- // isInited = false ;
- // }
- // }
- // void Logger::init() {
- // if ( !isInited ) {
- // sOutputStream.open(kLogFileName , ios_base::app ) ;
- // if ( !sOutputStream.good() ) {
- // cerr << "Unable to initialied the Logger !" << endl ;
- // return ;
- // }
- // isInited = true ;
- // }
- // }
- Logger& Logger::instance() {
- return sInstance ;
- }
- Logger::~Logger() {
- sOutputStream.close() ;
- }
- Logger::Logger() {
- sOutputStream.open( kLogFileName , ios_base::app) ;
- if ( !sOutputStream.good() ) {
- cerr << "Unable to initialied the Logger !" << endl ;
- }
- }
- /*
- * Test.cpp
- */
- #include "Logger.h"
- #include <vector>
- #include <string>
- #include <fstream>
- using namespace std ;
- int main( int agrc , char** argv ) {
- Logger::instance().log("Test Message" , Logger::kLogLevelDebug) ;
- vector<string> items ;
- items.push_back( "item1" ) ;
- items.push_back( "item2" ) ;
- Logger::instance().log( items , Logger::kLogLeveleError ) ;
- return 0 ;
- }
阅读(831) | 评论(0) | 转发(0) |