C + + design mode from 0 attack to single case mode

Source: Internet
Author: User

Singleton mode (Singleton) Intentions

Single-Case mode

Ensure that a class has only one instance and provides a global access point to access it. Applicability
    • When a class can have only one instance and the customer can access it from a well-known access point.
    • When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.
Singleton mode (Singleton)I have 6 beautiful wives, their husbands are me, I am our home husband Sigleton, they just say "husband", all refers to the same person, that is I (just had a dream, which has such a good thing) Singleton mode: Singleton mode to ensure that a class has only one instance, It also instantiates itself and provides this instance singleton pattern to the entire system. Singleton mode should only be used when there is a real "single instance" requirement.
Class Singleton{private:static Singleton * single; Singleton () {}public:static Singleton * getinstance () {if (single = NULL) Single = new Singleton (), return single;}; Singleton * Singleton::single = null;int _tmain (int argc, _TCHAR argv[]) {Singleton * S1 = singleton::getinstance (); Singleton * s2 = singleton::getinstance (); if (S1 = = s2) cout << "Same" << endl;else cout << "Different" &L t;< Endl;}

The implementation point of the Singleton mode: 1. The constructor is private (external cannot be new), and its own object as a member variable is also private and static, because the function of the returned instance is static, so the member variable should also be static

C + + design mode from 0 attack to single case mode

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.