I understand the design pattern (C ++ implementation) -- Singleton pattern)

Source: Internet
Author: User

The Singleton mode, as the name implies, is that only one instance can be used, so we must ensure that

  1. This class cannot be copied.
  2. This class cannot be publicly created.

For C ++, neither the constructor, the copy constructor nor the value assignment function can be publicly called.

However, you can construct a private constructor in two ways:

  1. Only when classes need to be modified (that is, the lazy Mode)
  2. I constructed it before the program starts, and you can use it directly (that is, in the hungry Chinese mode)

Let me talk about these two modes respectively:

  • In lazy mode, static local variables are initialized only once, that is, when the first execution is performed, their lifecycles are the same as those of the program. This is also applicable to multithreading.
    class single1{public:static single1& getInstance(){static single1 instance;return instance;}int helloSingle() {return 1;}private:private:single1(){};single1(const single1&);single1& operator=(const single1&);};

  • However, the system calls the construction of its instance before the main function. This is the initialization of the static instance. C/C ++ will ensure that it is performed before entering the main function.
    class single2{public:static single2* getInstance(){return mInstance;}int helloSingle() {return 1;}private:static single2* mInstance;private:single2(){};single2(const single2&);single2& operator=(const single2&);};single2* single2::mInstance = new single2;

We use static local variables and static instance features so that both of our modes are applicable to multithreading.

Lcl_data was originally created in csdn. Net [http://blog.csdn.net/lcl_data/article/details/8709701]

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.