您的位置:首页 > 编程语言 > C语言/C++

C++的单例模式

2013-05-11 16:04 155 查看
Student.h

[code][code] 


#ifndef __SINGLETON_H__


#define __SINGLETON_H__


 


#include <memory>


 


template<class T>


class SingleT


{


public:


static T * Instance()


   {


if (!p)


  {


p = new T;


}


 


return p;


}


 


static void Create()


   {


if (!p)


  {


p = new T;


}


}


 


static void Destroy()


   {


if (p)


  {


delete p;


p = NULL;


}


}


 


static T * Get()


   {


return p;


}


 


static void Reset()


   {


Destroy();


Create();


}


 


protected:


static T * p;


};


 


template <class T>


T * SingleT<T>::p = NULL;


 


#endif


 

[/code]
[/code]

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


[code]
[code] 


#ifndef __SINGLETONTEST_H__


#define __SINGLETONTEST_H__


 


#include "Singleton.h"


 


#include <iostream>


 


class SingletonTest : public SingleT<SingletonTest>


{


public:


SingletonTest(){};


~SingletonTest(){};




public:


inline void test(){std::cout<<"test()"<<std::endl;}


};


 


#endif

[/code]
[/code]

 

调用测试:SingletonTest::Instance()->test();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: