题目:C++设计模式:Singleton的模板实现之一 类型:原创
作者:古斌亮 时间:2002.12.25 EMail : [email protected]
在http://www.csdn.net/ 和天极网 看了两篇关于设计模式:Singleton的C++实现的文章, 自觉的学到不少东西(:)),在这里我也写了一个C++模板的实现之一,望各位大虾多多指教,也希望可以达到抛砖引玉的作用.
关于的Singleton的原理可以参考天极网《C++设计模式之Singleton》或http://www.csdn.net/中的《Singleton模式的C++实现研究》或是书本《设计模式》,这里就不说了,请多包涵!
翠花,上代码!
///////////////////////////////// //singleton template file //SingleEx.h
#ifndef SINGLETONEX__H__ #define SINGLETONEX__H__
//File Name : SingletonEx.h //作用 : 提供单件模板功能(singleton template) //Copyright(C) C++ //Microsoft Visual C++ 6.0 , GCC Ver2.95.3-6 编译通过 //作者:古斌亮 //时间:2002.12.25 //EMail : [email protected]
template<class T> class CSingletonBase { protected: inline static T* Create(void) { if(m_pt==NULL) { m_pt=new T(); } return m_pt; }
inline static void Free(void) { delete m_pt; m_pt=NULL; }
protected: CSingletonBase() { }
virtual ~CSingletonBase() { delete m_pt; }
private: CSingletonBase(const CSingletonBase& sig) { }
CSingletonBase& operator = (const CSingletonBase& sig) { }
private: static T * m_pt; };
template<class T> T* CSingletonBase<T>::m_pt = NULL;
template<class T> class CSingletonEx : private CSingletonBase<T> { public: CSingletonEx() { }
virtual ~CSingletonEx() { }
public: virtual T* Instance(void) { return CSingletonBase<T>::Create(); }
virtual void Release(void) { CSingletonBase<T>::Free(); }
private: CSingletonEx(const CSingletonEx& sig) { }
CSingletonEx& operator = (const CSingletonEx& sig) { } };
#endif //SINGLETONEX__H__
//////////////////////////////// //测试类 //Doc.h
#ifndef CDOC__H__ #define CDOC__H__
class CDoc //测试类 { public: CDoc(const std::string name = "NoName"):m_name(name){} virtual ~CDoc(){}
public: inline std::string Name() { return m_name; }
inline void SetName(const std::string& name) { m_name=name; }
protected: std::string m_name; };
#endif //CDOC__H__
//////////////////////////////////// //测试文件 //main.cpp
#include<iostream> #include<string> #include "singletonex.h" #include "doc.h"
void TestSingletonEx(void) { CSingletonEx<CDoc> s;
CDoc *pdoc = s.Instance();
std::cout<<pdoc->Name()<<std::endl;
pdoc->SetName("pdoc change: My SingletonEx");
CDoc *p2 = s.Instance();
std::cout<<p2->Name()<<std::endl;
p2->SetName("p2 change: SingletonEx ");
std::cout<<pdoc->Name()<<std::endl; }
void main(void) { std::cout<<"******** Test SingletonEx Start ******** "<<std::endl; TestSingletonEx(); }
//the end!! 
|