Singleton mode is a kind of common software design pattern. In its core structure, there is only one special class that is called a singleton. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system. If you have a lot of places that you need to use for singleton mode, you can simplify the coding of the singleton mode by using a macro instead. Note that the scheme is non-thread safe!
Declare before using the header file of the singleton: Declare_singleton (ClassA)
Then add a macro to the CPP file: Implement_singleton (ClassA)
External call Method: Classa::instance ()
/** singleton.h * * Created on:may * Author:yanghui*/#ifndef Singleton_h_#defineSingleton_h_#defineDeclare_singleton (ClassName)Private: StaticClassName *Singleton_; Public: StaticClassName *getinstance (); Static voidreleaseinstance ();#defineImplement_singleton (ClassName) \ClassName*classname::singleton_ =NULL; ClassName*classname::getinstance () {if(Singleton_ = =NULL) {Singleton_=NewClassName (); } returnSingleton_; } voidclassname::releaseinstance () {if(Singleton_! =NULL) {Delete Singleton_; Singleton_=NULL; } }#endif/* Singleton_h_ */
Singleton mode (supplemental)