Use macro-implemented Singleton Mode

Source: Internet
Author: User

 

I personally think it is more convenient to use

 

# Define SINGLETON_CLASS_NO_DEF_CONSTRUCT_BODY (class_name )\

Private :\

Class_name ();\

Class_name (const class_name &);\

Class_name & operator = (const class_name &);\

Public :\

Static class_name & Instance ()\

{\

Static class_name one ;\

Return one ;\

}

 

# Define SINGLETON_CLASS (class_name )\

Private :\

Class_name (){}\

Class_name (const class_name &);\

Class_name & operator = (const class_name &);\

Public :\

Static class_name & Instance ()\

{\

Static class_name one ;\

Return one ;\

}

 

The difference between two macros is only that the default no-argument constructor is implemented. Example:

 

// HostBasicInformation. h

Class HostBasicInformation

{

SINGLETON_CLASS_NO_DEF_CONSTRUCT_BODY (HostBasicInformation)

 

Public:

Virtual ~ HostBasicInformation ();

Std: string GetInstallCode ();

};

 

// HostBasicInformation. cpp

 

// If SINGLETON_CLASS is used, no parameter-free constructor needs to be defined.

HostBasicInformation: HostBasicInformation (){

 

}

 

 

 

HostBasicInformation ::~ HostBasicInformation (){

 

}

 

Std: string HostBasicInformation: GetInstallCode ()

{

Return "";

}

 

The main advantage of this macro method is that it can strictly limit the use of this type, that is, it can only be used as a singleton.

 

Std: string str_installCode = HostBasicInformation: Instance (). GetInstallCode ();

Related Article

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.