zoukankan      html  css  js  c++  java
  • C++设计模式之单例模式

    源代码在VC++ 6.0通过编译

     1 //SingletonHeader.h
     2 #include <IOSTREAM>
     3 #include <FSTREAM>
     4 #include <VECTOR>
     5 
     6 class Logger{
     7 public:
     8     static const std::string kLogLevelDebug;
     9     static const std::string kLogLevelInfo;
    10     static const std::string kLogLevelError;
    11     
    12     static Logger& instance();
    13 
    14     //Logs a single message at the given log level
    15     void log(const std::string& inMessage,
    16         const std::string& inLogLevel);
    17     //Logs a vector of message at the given log level
    18     void log(const std::vector<std::string>& inMessages,
    19         const std::string& inLogLevel);
    20     
    21     
    22 protected:
    23     static Logger sInstance;
    24     static const char* const kLogFileName;
    25     std::ofstream mOutputStream;
    26     
    27 private:
    28     Logger();
    29     virtual ~Logger();
    30 };
    View Code
     1 //SingletonHeader.cpp
     2 #include "SingletonHeader.h"
     3 #include <STRING>
     4 using namespace std;
     5 
     6 const string Logger::kLogLevelDebug = "DEBUG";
     7 const string Logger::kLogLevelInfo = "INFO";
     8 const string Logger::kLogLevelError = "ERROR";
     9 
    10 const char* const Logger::kLogFileName = "log.out";
    11 
    12 Logger Logger::sInstance;
    13 
    14 Logger& Logger::instance()
    15 {
    16     return sInstance;
    17 }
    18 
    19 Logger::Logger()
    20 {
    21     mOutputStream.open(kLogFileName,ios_base::app);
    22     if (!mOutputStream.good())
    23     {
    24         cerr<<"Unable to initialize the Logger!"<<endl;
    25     }
    26 }
    27 
    28 Logger::~Logger()
    29 {
    30     mOutputStream.close();
    31 }
    32 
    33 
    34 void Logger::log(const string& inMessage, const string& inLogLevel)
    35 {
    36     mOutputStream << inLogLevel << ":" << inMessage << endl;
    37 }
    38 
    39 void Logger::log(const vector<string>& inMessages, const string& inLogLevel)
    40 {
    41     for (size_t i=0;i<inMessages.size();i++)
    42     {
    43         log(inMessages[i],inLogLevel);
    44     }
    45 }
    46 
    47 int main(int argc, char **argv)
    48 {
    49     Logger::instance().log("test message",Logger::kLogLevelDebug);
    50     vector<string> items;
    51 
    52     items.push_back("item1");
    53     items.push_back("item2");
    54 
    55     Logger::instance().log(items,Logger::kLogLevelError);
    56 
    57     return 0;
    58 }
    View Code
  • 相关阅读:
    什么是wsgi,uwsgi,uWSGI
    Flask 和 Django 路由映射的区别
    简述浏览器通过WSGI请求动态资源的过程
    前端qq交流群
    python qq交流群
    python 魔法方法 __str__和__repr__
    python 使用for 实现死循环
    查看Django版本
    pep8 python 编码规范
    python random.randint(9,10)结果是什么?
  • 原文地址:https://www.cnblogs.com/jeromesunny/p/3224193.html
Copyright © 2011-2022 走看看