用模板实现单例模式
方法1
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
template <typename T>
class Singleton
{
public:
static T& GetInstance() //静态成员函数,全局
{
static T instance; //创建一个静态局部对象
//此处必须要static,否则构造完成,就析构了
return instance;
}
private:
Singleton();
Singleton(const Singleton& other);
Singleton& operator= (const Singleton& other);
~Singleton();
//static T* instance_;
};
//template <typename T>
//T* Singleton<T>::instance_ = 0;
#endif // _SINGLETON_H_
#include "Singleton.h"
#include<iostream>
using namespace std;
class ApplicationImpl
{
public:
ApplicationImpl()
{
cout << "ApplicationImpl..." << endl;
}
~ApplicationImpl()
{
cout << "~ApplicationImpl..." << endl;
}
void Run()
{
cout << "Run ..." << endl;
}
private:
};
typedef Singleton<ApplicationImpl> Application;
int main(void)
{
//Singleton<ApplicationImpl> a; //Error : 由于Singleton构造函数时私有的,无法访问,就无法用Singleton来构造对象
Application::GetInstance().Run();
Application::GetInstance().Run();
return 0;
}
方法2(推荐)
atexit()函数
用atexit()函数,该函数为注册函数,可以将其它函数注册进来。在程序结束后,会先调用注册的函数,再结束程序,优先调用后注册的函数
包含的头文件: < cstdlib >
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include<cstdlib>
using namespace std;
template <typename T>
class Singleton
{
public:
static T& GetInstance() //静态成员函数,全局
{
Init();
return *instance_;
}
private:
static void Init()
{
if (instance_ == 0)
{
instance_ = new T;
atexit(Destory);
}
}
static void Destory()
{
delete instance_;
}
static T* instance_;
Singleton();
Singleton(const Singleton& other);
Singleton& operator= (const Singleton& other);
~Singleton();
};
template <typename T>
T* Singleton<T>::instance_ = 0; //static成员需在外部初始化
#endif // _SINGLETON_H_
#include "Singleton.h"
#include<iostream>
class ApplicationImpl
{
public:
ApplicationImpl()
{
cout << "ApplicationImpl..." << endl;
}
~ApplicationImpl()
{
cout << "~ApplicationImpl..." << endl;
}
void Run()
{
cout << "Run ..." << endl;
}
};
typedef Singleton<ApplicationImpl> Application;
int main(void)
{
//Singleton<ApplicationImpl> a; //Error : 由于Singleton构造函数时私有的,无法访问,就无法用Singleton来构造对象
Application::GetInstance().Run();
Application::GetInstance().Run();
return 0;
}
模板动态创建对象
见72cpp