当前位置:网站首页>Relatively perfect singleton mode

Relatively perfect singleton mode

2022-06-11 21:39:00 LeoTsou

Relatively perfect singleton mode

There is no need to say more about the singleton mode , However, when learning design patterns for the first time, it is inevitable to encounter the problem that copy construction is not considered when using singleton patterns .
Here we will try to implement several relatively perfect and extensible singleton patterns , For reference .

Hello World edition

class Singleton {
public:
Singleton *GetInstance() {
    if (mThis != NULL)
	return mThis;
	mThis = new Singleton;
}
private:
    static Singleton *mThis;
    Singleton() {}
};

A better version

A perfect class should consider the problem of copy construction , So a more complete version is just around the corner :

class Singleton {
public:
Singleton *GetInstance() {
    if (mThis != NULL)
        return mThis;
	mThis = new Singleton;
}
private:
    static Singleton *mThis;
    Singleton() {}
    Singleton(Singleton &obj) {/* ... */} //  Handle the problem of copy construction 
};

A simpler version

If you happen to be like me , Know some C++11 Knowledge , Then you can do it

class Singleton {
public:
Singleton *GetInstance() {
    if (mThis != nullptr)
        return mThis;
	mThis = new Singleton;
}
private:
    static Singleton *mThis;
    Singleton() {}
    Singleton(Singleton &obj) = delete; //  utilize C++11 Version of the property of 
};

Versions that consider extensibility

If you happen to be like me , Will consider the issue of scalability , Then you can do it

template <typename T>
class Singleton {
public:
template <typename T>
Singleton<T> *GetInstance() {
    if (mThis != NULL)
        return mThis;
    mThis = new Singleton<T>;
}
private:
    static Singleton<T> *mThis;
    Singleton<T>() {}
    Singleton<T>(Singleton &obj) = delete;  
};

Conclusion

The discussion on this topic is over .
As for other optimization methods for singleton mode , What kind of hungry man or thread , Predecessors have discussed a lot .
Only my thoughts are discussed here .

It's not easy to create , If you need to reprint, please attach the original url:https://www.cnblogs.com/leoTsou/p/16366818.html

原网站

版权声明
本文为[LeoTsou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112132410332.html