模板化的单例模式
android代码,模板实现的单例模式。
template <typename TYPE> class Singleton { public: static TYPE& getInstance() { Mutex::Autolock _l(sLock); TYPE* instance = sInstance; if (instance == 0) { instance = new TYPE(); sInstance = instance; } return *instance; } protected: ~Singleton() { }; Singleton() { }; private: Singleton(const Singleton&); Singleton& operator = (const Singleton&); static Mutex sLock; static TYPE* sInstance; };
//wtl中也有类似用法
//用法如下。 class OverlayMgr : public Singleton<OverlayMgr> { }
template<class T>
class Singleton{
public:
static T* getInstance(){
if(ptr==NULL){
ptr=new T();//(T*)(::operator new(sizeof(T)));
}
return ptr;
}
private:
Singleton(){};
static T* ptr;
};
template<typename T>
T* Singleton<T>::ptr=0;
class C{
public:
int x;
C(){
x=0;
}
~C(){
cout<<"C delete"<<endl;
}
};
int main(){
C* c=Singleton<C>::getInstance();
C* d=Singleton<C>::getInstance();
cout<<c<<" "<<d<<endl;
}
//改良 T本身的构造函数私有. Singleton是T的友元
多模块(多个so文件),在多个so中模板展开,测试,正常.class Singleton{
public:
static T* getInstance(){
if(ptr==NULL){
ptr=new T();//(T*)(::operator new(sizeof(T)));
}
return ptr;
}
private:
Singleton(){};
static T* ptr;
};
template<typename T>
T* Singleton<T>::ptr=0;
class C{
public:
int x;
C(){
x=0;
}
~C(){
cout<<"C delete"<<endl;
}
};
int main(){
C* c=Singleton<C>::getInstance();
C* d=Singleton<C>::getInstance();
cout<<c<<" "<<d<<endl;
}
//改良 T本身的构造函数私有. Singleton是T的友元
762

被折叠的 条评论
为什么被折叠?



