Singletons

构造函数是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);
...
},
依存性导致对象捆绑,不好用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值