這些東西在網上都很多了,但是我覺得他們的使用都不符合我的要求,所以自己動手豐衣足食,寫一個自己能用的,夠用就好。
#include <iostream>
?
using namespace std;
?
//單件模板類
template<typename T> class Singleton
{
protected:
?
? static T* m_Instance;
?
? Singleton(){}
? virtual~Singleton(){}
?
public:
?
? //實例的獲得
? static T* Instance()
? {
??? if(m_Instance==0)
????? m_Instance=new T;
?
??? return m_Instance;
? }
?
? //單件類的釋放
? virtual void Release()
? {
??? if(m_Instance!=0)
??? {
????? delete m_Instance;
????? m_Instance=0;
??? }
? }
};
?
//單件模板測試類
class Test:public Singleton<Test>
{
? friend class Singleton<Test>; //聲明為友員,不然會出錯
protected:
? Test()
? {
??? a=b=c=0;
? }
? virtual ~Test(){}
?
public :
?
? int a;
? int b;
? int c;
};
?
//初始化靜態成員。。。
template<> Test*Singleton<Test>::m_Instance=0;
?
?
//以下為測試代碼
void main()
{
? Test*t=Test::Instance();
?
? t->a=5;
? t->b=25;
? t->c=35;
? cout<<"t: a="<<t->a<<" b="<<t->b<<" c="<<t->c<<endl;
?
? Test*t2;
? t2=Test::Instance();
? cout<<"t2 a="<<t2->a<<" b="<<t2->b<<" c="<<t2->c<<endl;
?
? t2->Release();
}
|