Summary of using the use of Singleton

zhaozj2021-02-17  51

Design Pattern is undoubtedly a book that each programmer should read. This book gives 23 Pattern, which is Singleton Pattern, here, I probably introduced it to use Singleton. Some practices, I hope to have some help.

The main intended Single Pattern is to ensure that there is only one example and to ensure a global access point access to it.

Applicable situations depend on its state, and it must change its status at runtime One action contains a huge Switch & Case statement

Advantages It will be locally locally related to specific states, so that new status and conversions can be added by defining new subclasses.

Practice 1:

Because there is not mentioned in the book, how to delete the M_Pinstance pointer, so provide the exitInstance () method manually deleted

Class Csingleton {public: Virtual ~ csingleton ();

Static csingleton * instance (void) {if (null == m_pinstance) return m_pinstance = new csingleton; return m_pinstance;

Void ExitInstance (Void)

{delete m_pinstance;}

Private

CSITON ();

Static t * m_pinstance;

}

Csingleton * csingleton :: m_pinstance = null;

Practice 2:

Add a nested class in the class, so that this nested class is responsible for deleting m_pinstance (similar to the principle of Auto_PTR)

class CSingleton {public: virtual ~ CSingleton (); static CSingleton * Instance () {if (NULL == m_pInstance) m_pInstance = new CSingleton; return m_pInstance;} private: CSingleton (); static CSingleton * m_pInstance; class Cleaner {public: ~ Cleaner () {delete m_pinstance;}} Friend Csingleton :: CleaNer; Static Csingleton :: CleaNer CleaNer;

Csingleton * csingleton :: m_pinstance = null; csingleton :: Cleaner Csingleton :: CleaNer;

Practice 3:

Using Template features, build a template class about Singleton, any class you want to use Singleton Pattern, you can inherit from it here.

Template class csingleton {public: static t * instance (void) {static t instance; return

Protected: csingleton () {}; virtual ~ csingleton () {};

Private: csingleton (const csingleton & source) {};

If the class ctest wants to use the Singleton feature ctest: Public Csingleton

{

Friend Csingleton ;

Ctest ();

PUBLIC:

~ Ctest ();

}

At present, I use the last way, it is more convenient, and it is more convenient to write a large pile of code for each class that needs to use similar techniques.

I hope to be helpful

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

New Post(0)