求C++的单例体模式的一个简单实例并加详解
如题
[解决办法]
#include <iostream>
using namespace std;
class CBass
{
public:
static CBass* CreateBase()
{
if (m_base == NULL)
m_base = new CBass();
return m_base;
}
static void DeleteBase()
{
if (m_base != NULL)
{
delete m_base;
m_base = NULL;
}
}
void Show()
{
cout << "CBase::Show()" << endl;
}
protected:
CBass()
{
cout << "CBase::CBase()" << endl;
}
~CBass()
{
cout << "CBase::~CBase()" << endl;
}
static CBass* m_base;
};
CBass* CBass::m_base = NULL;
int _tmain(int argc, _TCHAR* argv[])
{
CBass::CreateBase()->Show();
CBass::DeleteBase();
return 0;
}
**************************************************************Singleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();//此处声明为了保护 则无法实现继承
private:
static Singleton* _instance;
};
#endif //~_SINGLETON_H_
**************************************************************Singleton.cpp
#include "Singleton.h"
#include <iostream>
using namespace std;
Singleton* Singleton::_instance = 0;
Singleton::Singleton()
{
cout<<"Singleton...."<<endl;
}
Singleton* Singleton::Instance()
{
if (_instance == 0)
{
_instance = new Singleton();
}
return _instance;
}
//创建全局唯一一个对象
***************************************************************************main.cpp
#include"Singleton.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
Singleton* sgn = Singleton::Instance();
// Singleton* sgn = Singleton::Instance();
//不会再创建了 因为_instance=0才创建一旦创建就不在new 了
system("pause");
return 0;
}