为什么要用double check呢?因为当已经有instance存在,每次想新建instance时,我们就不需要先启用lock machnism,直接通过判定条件拒绝就行了。
class Singleton{
static Singleton *pInstance;
public:
static Singleton *instance();
...
}
Singleton* Singleton::instance() {
if(pInstance == 0) {
// 1st test
Lock lock;
if(pInstance == 0) {
// 2nd test
pInstance = new Singleton;
}
}
return pInstance;
}
No comments:
Post a Comment