Singleton mode (supplemental)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.