• C++的单例模式


    Student.h

       1:  
       2: #ifndef __SINGLETON_H__
       3: #define __SINGLETON_H__
       4:  
       5: #include <memory>
       6:  
       7: template<class T>
       8: class SingleT
       9: {
      10: public:
      11:     static T * Instance()
      12:     {
      13:         if (!p)
      14:         {
      15:             p = new T;
      16:         }
      17:  
      18:         return p;
      19:     }
      20:  
      21:     static void Create()
      22:     {
      23:         if (!p)
      24:         {
      25:             p = new T;
      26:         }
      27:     }
      28:  
      29:     static void Destroy()
      30:     {
      31:         if (p)
      32:         {
      33:             delete p;
      34:             p = NULL;
      35:         }
      36:     }
      37:  
      38:     static T * Get()
      39:     {
      40:         return p;
      41:     }
      42:  
      43:     static void Reset()
      44:     {
      45:         Destroy();
      46:         Create();
      47:     }
      48:  
      49: protected:
      50:     static T * p;
      51: };
      52:  
      53: template <class T>
      54: T * SingleT<T>::p = NULL;
      55:  
      56: #endif
      57:  

    定义另外一个测试类:SingletonTest.h

       1:  
       2: #ifndef __SINGLETONTEST_H__
       3: #define __SINGLETONTEST_H__
       4:  
       5: #include "Singleton.h"
       6:  
       7: #include <iostream>
       8:  
       9: class SingletonTest : public SingleT<SingletonTest>
      10: {
      11: public:
      12:     SingletonTest(){};
      13:     ~SingletonTest(){};
      14:     
      15: public:
      16:     inline void test() {std::cout<<"test()"<<std::endl;}
      17: };
      18:  
      19: #endif

    调用测试:SingletonTest::Instance()->test();

  • 相关阅读:
    socket选项设置
    shell 备忘录
    VIM中cscope和tags数据库的添加
    MFC程序设计中的BeginPaint/EndPaint和GetDC/ReleaseDC的使用
    shell 命令行参数解析
    do{...}while(0)用法总结
    0长度数组的使用
    在线帮助文档
    GCC编译器帮助文档
    几款优秀的Linux基准测试工具
  • 原文地址:https://www.cnblogs.com/meteoric_cry/p/3072849.html
Copyright © 2020-2023  润新知