Singletons

来源:互联网 发布:plsql备份oracle数据库 编辑:程序博客网 时间:2024/05/21 19:20
构造函数是private,客户端无法产生Singletons,但Instance()使得其编译期就得以实施
class Singleton{
public :
static Singleton * Instance(){
if(!pInstance_)
pInstance_=new Singleton;
return pInstance_;
}
}
private:
Singleton();
Singleton(const Singleton&);
Singleton &operator=(const Singleton&);
~Singleton& operator =(const Singleton&);
static Singleton *pInstance_;
};
防止Singleton对象所访问的资源泄露,采用如下机制
Singleton& Singleton::Instance(){
static Singleton obj;
return obj;
}
编译器处理析构。
当Singleton对象存在前后关系的时候,检测dead reference问题
class Singleton
{
public:
static Singleton& Instance()
{
if(!pInstance_)
{
if(destoryed_)
OnDeadReference();
else
Create();
}
}
return *pInstance_;
}
private:
static void Create()
{
static Singleton theInstance;
pInstance_=&theInstance;
}
static void OnDeadReference()
{
throw std::runtime_error("Dead Refernce Detected");
}
virtual ~Singleton(){
pInstance_=0;
destroryed_=true;
}
static Singleton *pInstance_;
static bool destroyed_;
};
Singleton * Singleton::pInstance_=0;
bool Singleton::destoryed_ =  false;


Phoenix Singleton 重新生成已被销毁对象
void Singleton::OnDeadReference()
{
Create();
new(pInstance_)Singleton;    //并不分配空间
atexit(KillPhoenixSingleton);
destroryed_=false;
}
void Singleton::KillPhoenixSingleTon()
{
pInstance_->~Singleton();
}
atexit()不能嵌套登记
需要注意析构和重新构造的两个是时刻间的状态


对象寿命控制方法
class SomeSingleton{...};
class SomeSing{...};


SomeClass * pGlobalObject(new SomeClass);
int main()
{
SetLongevity(&SomeSingleton(),Instance(),5);
SetLongevity(pGlobalObject,6);
}
template<typename T>
void SetLongevity(T* pDynObject,unsigned int longevity);
SetLongevity 只处理new分配而得的对象。
建立依存性管理器
class DependencyManager
{
public :
template<typename T ,typename U>
void SetDependency(T &dependent,U &target);
...
},
依存性导致对象捆绑,不好用
0 0
原创粉丝点击