求C++的单例体模式的一个简单实例并加详解如题[解决办法]C/C++ code#include iostreamusing namespace s
求C++的单例体模式的一个简单实例并加详解
如题
[解决办法]
- C/C++ code
#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;}
[解决办法]
对象只要利用自己的属性完成了自己的任务,那该对象就是承担了责任。除了维持了自身的一致性,该对象无需承担其他任何责任。 如果该对象还承担着其他责任,而其他对象又依赖于该特定对象所承担的责任,我们就需要得到该特定对象。
将类的责任集中到唯一的单体对象中,确保该类只有一个实例,并且为该类提供一个全局访问点。这就是单体模式的目的。
单体模式的难点不在于单体模式的实现,而在于在系统中任何识别单体和保证单体的唯一性。
- C/C++ code
**************************************************************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; } 