zoukankan      html  css  js  c++  java
  • C++ Singleton

    File:singleton.hpp

     1 #ifndef __SINGLETON_HPP_
     2 #define __SINGLETON_HPP_
     3 
     4 template <class T>
     5 class Singleton
     6 {
     7 public:
     8   static T* Instance() {
     9       if(!m_pInstance) m_pInstance = new T;
    10       assert(m_pInstance !=NULL);
    11       return m_pInstance;
    12   }
    13 protected:
    14   Singleton();
    15   ~Singleton();
    16 private:
    17   Singleton(Singleton const&);
    18   Singleton& operator=(Singleton const&);
    19   static T* m_pInstance;
    20 };
    21 
    22 template <class T> T* Singleton<T>::m_pInstance=NULL;
    23 
    24 #endif

    Usage:

     1 #include "singleton.hpp"
     2 
     3 class Logger
     4 {
     5 public:
     6    Logger() {};
     7    ~Logger() {};
     8    bool openLogFile(string);
     9    void writeToLogFile(string);
    10    bool closeLogFile(string);
    11 private:
    12    ...
    13    ...
    14 };
    15 
    16 bool Logger::openLogFile(std::string)
    17 {
    18    ...
    19    ...
    20 }
    21 
    22 ...
    23 ...
    24 
    25 typedef Singleton<Logger> LoggerSingleton;   // Global declaration
    26 
    27 main()
    28 {
    29     ...
    30 
    31     LoggerSingleton::Instance()->openLogFile("logFile.txt");
    32 
    33     ...
    34 }

    来自:http://www.yolinux.com/TUTORIALS/C++Singleton.html

     

  • 相关阅读:
    Python文件的两种用途
    模块的搜索路径
    循环导入问题
    import和from...import
    模块的四种形式
    函数小结
    面向过程编程
    内置函数
    匿名函数
    递归
  • 原文地址:https://www.cnblogs.com/good90/p/2654113.html
Copyright © 2011-2022 走看看