zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    vue-cli项目打包出现空白页和路径错误问题
    Git操作手册
    Atom Editor 插件 atom-less 的使用方法
    Vue搭建
    使绝对定位高宽自适应
    原生JS表单序列化
    前端代码有关搜索引擎的代码
    网页局部打印
    万维网
    浅淡传统企业进入移动互联网的几种方式
  • 原文地址:https://www.cnblogs.com/meteoric_cry/p/3072849.html
Copyright © 2011-2022 走看看