Learn the design mode from another perspective-singleton Mode

Source: Internet
Author: User

There can only be one belief.

The Singleton mode is as literal as it means: only one instance can be created. At first glance, think about how it is possible to create countless instances as long as it is a class. Let's take a look at how God makes himself unique.

① God can create everything, and everything cannot create God. The method is to hide the construction method of "God ".

Class God

{

PRIVATE:

God ();

~ God ();

}

② Who created God? He can only be himself now.

Class God

{

PRIVATE:

Static god * _ godinstance;

Protected:

God ();

~ God ();

Public:

Static god * godinstance ();

}

God * God: _ godinstance = 0;

God * God: godinstance ()

{

_ Godinstance = new god ();

Return _ godinstance;

}

③ The constructor is hidden to prevent god from being freely created by others.

Class God

{

PRIVATE:

Static god * _ godinstance = 0; // use static to make the Variable _ godinstance initial

// Only executed during the first class instantiation

PRIVATE:

God ();

~ God ();

Public:

Static god * godinstance ();

}

God * God: _ godinstance = 0;

God * God: godinstance ()

{

If (godinstance = 0)

{

_ Godinstance = new god ();

}

Return _ godinstance;

}

④ Believers can only declare the existence of God.

Int * Main (INT argc, char * argv [])

{

God * SGN = God: godinstance ();

}

 

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.