《C++高级编程》第二十六章的一个例子。
/**
* Logger.h
*
* Definition of a singleton logger class, implemented with static methods
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
class Logger
{
public:
static const std::string kLogLevelDebug;
static const std::string kLogLevelInfo;
static const std::string kLogLevelError;
// Return a reference to the singleton logger object
static Logger& instance();
// Log a single message at the given log level
void log(const std::string& inMessage, const std::string& inLogLevel);
// Log a vector of messages at the given log level
void log(const std::vector<std::string>& inMessage, const std::string& inLogLevel);
protected:
// static variable for the one-and-only instance
static Logger sInstance;
// Constant for the filename
static const char* const kLogFileName;
// Data member for the output stream
std::ofstream mOutputStream;
private:
// 关键:私有的构造函数,不能实例化,因为实例化时类外部无法访问其内部的私有的构造函数
Logger(void);
~Logger(void);
};
/**
* Logger.cpp
*
* Implementation of a singleton logger class
*/
#include "Logger.h"
#include <string>
using namespace std;
const string Logger::kLogLevelDebug = "DEBUG";
const string Logger::kLogLevelInfo = "INFO";
const string Logger::kLogLevelError = "Error";
const char* const Logger::kLogFileName = "log.out";
// The static instance will be construct when the program starts and destructed when it ends.
Logger Logger::sInstance;
Logger::Logger(void)
{
mOutputStream.open(kLogFileName, ios_base::app);
if (!(mOutputStream.good())) {
cerr << "Unable to initialize the Logger!" << endl;
}
}
Logger::~Logger(void)
{
mOutputStream.close();
}
Logger& Logger::instance()
{
return sInstance;
}
void Logger::log(const std::string& inMessage, const std::string& inLogLevel)
{
mOutputStream << inLogLevel << ":" << inMessage << endl;
}
void Logger::log(const std::vector<std::string>& inMessage, const std::string& inLogLevel)
{
for (size_t i=0; i<inMessage.size(); i++) {
log(inMessage[i], inLogLevel);
}
}
// TestTrueSingletonLogger.cpp
#include "Logger.h"
#include <vector>
#include <string>
int main(int argc, 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::kLogLevelError);
return 0;
}