157 recommendations for writing high-quality code to improve C # programs--Recommendation 105: Using private constructors to harden a single case

Source: Internet
Author: User

Recommendation 105: Use private constructors to harden a single case

Singleton refers to a type that generates only one instance object. A simple implementation of the singleton is as follows:

        Static voidMain (string[] args)        {Singleton.Instance.SampleMethod (); }     Public Sealed classSingleton {StaticSingleton instance =NULL;  Public StaticSingleton Instance {Get            {                returninstance==NULL?NewSingleton (): instance; }        }         Public voidSampleMethod () {//omitted        }    }

A singleton type singleton is used in the main method.

The singleton first provides a private variable of its own type. In the instance property, it is the only instance responsible for creating the type itself. If you want to use the type externally, you must pass the instance property, with a special emphasis on the "must" two words.

There is a problem in the code above: although in the caller code, we get the type instance through the instance property. However, the type does not prevent itself from being created externally. Because the type singleton does not provide a construction method, the compiler creates a constructor for it by default, and the access modifier for the default constructor is public. This will not prevent the following code from being used externally:

            New Singleton ();            S.samplemethod ();

This obviously loses the meaning of a single case. In fact, this causes multiple singleton objects to be present in the system. To prevent this from happening, you must add a private constructor for the singleton type. The improved version of Singleton is as follows:

     Public Sealed classSingleton {StaticSingleton instance =NULL; //restrict instances from being created externally        PrivateSingleton () {} Public StaticSingleton Instance {Get{returnInstance = =NULL?NewSingleton (): instance;} }         Public voidSampleMethod () {//omitted        }    }

Note: The final singleton is not thread-safe. In the case of multithreading, it is possible to produce a second instance. One of the most famous techniques for a single case is the "double locking" technique. With double locking, the thread-safe version of the Singleton is:

     Public Sealed classSingleton {StaticSingleton instance =NULL; Static ReadOnly Objectpadlock=New Object(); //restrict instances from being created externally        PrivateSingleton () {} Public StaticSingleton Instance {Get            {                if(Instance = =NULL)                {                    Lock(padlock) {if(Instance = =NULL) {instance=NewSingleton (); }                    }                }                returninstance; }        }         Public voidSampleMethod () {//omitted        }    }

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 105: Using private constructors to harden a single case

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.