您的位置:首页 > 其它

单例

2016-05-11 16:49 375 查看
#ifndef __INCLUDE_SINGLETON_H__
#define __INCLUDE_SINGLETON_H__

#include <iostream>
#include <string.h>
#include <cstdlib>
using namespace std;

template<typename T>
class Singleton
{
public:
static T & GetInstance()
{
/*static T instance;  /*局部静态对象,程序结束后自动调用析构函数*/
/*return instance;*/
Init();
return *instance_;
}
private:
static void Init()
{
if ( instance_ == NULL)
{
instance_ = new T;
atexit(Destory);
}
}
static void Destory()
{
delete instance_;
}
Singleton() {}
Singleton(const Singleton<T> &single) {}
Singleton<T> & operator = (const Singleton<T> & sigle) {}
~Singleton() {}
static T *instance_;
};

template<typename T>
T* Singleton<T>::instance_ = NULL;
#endif //__INCLUDE_SINGLETON_H__
#include <iostream>
#include "Singleton.h"
using namespace std;

class ApplicationImpl
{
public :
ApplicationImpl()
{
cout<<"ApplicationImpl.."<<endl;
}
~ApplicationImpl()
{
cout<<"~ApplicationImpl.."<<endl;
}
void Run()
{
cout<<"Run.."<<endl;
}
};

typedef Singleton<ApplicationImpl> App;

int main()
{
App::GetInstance().Run();
App::GetInstance().Run();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: