前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++的单例模式

C++的单例模式

作者头像
meteoric
发布2018-11-19 16:36:59
8220
发布2018-11-19 16:36:59
举报
文章被收录于专栏:游戏杂谈游戏杂谈

Student.h

代码语言:javascript
复制
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

代码语言:javascript
复制
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();

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-05-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档