Singleton for inheritance (in C ++)

zhaozj2021-02-17  48

The Singleton mode proposed in the DP cannot be used to be used as inheritance base classes, and each time you have to design a Singleton class in accordance with Singleton's rules, especially when Singleton appears frequently. Singleton in the MCD is also outsourcing, this is a Singleton is used as a base class, but it is related to the language, and it is no problem in C .

Here is the implementation of this template class:

template class Singleton {private: static SubClass * _instance; static bool _create_by_instance; public: static SubClass * Instance (); protected: (! _ create_by_instance) Singleton () {if throw std :: runtime_error ( "can not create Object by subclass ";}}; template subclass * singleton :: instance () {i (_instance == 0) {_CREATE_BY_INSTANCE = true; // Indicate caller identity // abnormal processing TRY {_Instance = new SubClass ();} catch (...) {_create_by_instance = false; // logout call identity} _create_by_instance = false; // logout call identity} return _instance;} template SubClass * Singleton :: _ instance = 0; TEMP Late bool singleleton :: _ create_by_instance = 0;

Use very simple:

Class Machine: Public Singleton {...};

CLIENT if this: Machine Obj;

Or: Machine * PMCH = New Machine;

Both Singlet will throw an exception period. Once some people have filed that they can identify these abnormalities in the compile period, I think there is no way, at least I have never thought of the way, of course, may have a better way to have a better way to pass by Please note.

转载请注明原文地址:https://www.9cbs.com/read-29192.html

New Post(0)