C # Singleton mode

Source: Internet
Author: User

1, non-thread safe (Classic mode), but without regard to thread safety, may be problematic in multi-threading, but has never seen an error.

/// <summary>    ///the implementation of single-case pattern/// </summary>     Public classSingleton {//define a static variable to hold an instance of the class        Private StaticSingleton uniqueinstance; //define private constructors so that the outside world cannot create instances of that class        PrivateSingleton () {}/// <summary>        ///defining public methods provides a global access point, and you can also define public properties to provide global access points/// </summary>        /// <returns></returns>         Public StaticSingleton getinstance () {//created if an instance of the class does not exist, or is returned directly            if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }            returnuniqueinstance; }    }

2. Try thread safety (double lock)

  /// <summary>    ///the implementation of single-case pattern/// </summary>     Public classSingleton {//define a static variable to hold an instance of the class        Private StaticSingleton uniqueinstance; //define an identity to ensure thread synchronization        Private Static ReadOnly ObjectLocker =New Object(); //define private constructors so that the outside world cannot create instances of that class        PrivateSingleton () {}/// <summary>        ///defining public methods provides a global access point, and you can also define public properties to provide global access points/// </summary>        /// <returns></returns>         Public StaticSingleton getinstance () {//when the first thread runs here, the locker object is "locked" at this point ,//When the second thread runs the method, it first detects that the locker object is a "lock" state, and the thread suspends waiting for the first line threads unlocked//after the lock statement finishes running (that is, after the thread finishes running) The object is "unlocked"//double locking requires just one sentence.            if(Uniqueinstance = =NULL)            {                Lock(locker) {//created if an instance of the class does not exist, or is returned directly                    if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }                }            }            returnuniqueinstance; }    }

3. Simple thread

/// <summary>    ///the implementation of single-case pattern/// </summary>     Public classSingleton {//define a static variable to hold an instance of the class        Private StaticSingleton uniqueinstance; //define an identity to ensure thread synchronization        Private Static ReadOnly ObjectLocker =New Object(); //define private constructors so that the outside world cannot create instances of that class        PrivateSingleton () {}/// <summary>        ///defining public methods provides a global access point, and you can also define public properties to provide global access points/// </summary>        /// <returns></returns>         Public StaticSingleton getinstance () {//when the first thread runs here, the locker object is "locked" at this point ,//When the second thread runs the method, it first detects that the locker object is a "lock" state, and the thread suspends waiting for the first line threads unlocked//after the lock statement finishes running (that is, after the thread finishes running) The object is "unlocked"            Lock(locker) {//created if an instance of the class does not exist, or is returned directly                if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }            }            returnuniqueinstance; }    }

4, a Hungry man mode (this mode is characterized by its own active instance.) )

 Public Sealed class singleton{        privatestaticreadonly Singleton instance=new  Singleton ();          Private Singleton ()        {        }        publicstatic  Singleton getinstance ()        {                 return  instance;}        }

5, not completely lazy, but thread-safe and do not use locks.

 Public Sealed classsingleton{Private Static ReadOnlySingleton instance =NewSingleton (); //the static constructor that is displayed//no need to mark type-before field initialization    StaticSingleton () {}PrivateSingleton () {} Public StaticSingleton Instance {Get        {            returninstance; }    }}

6. Fully deferred instantiation

 Public Sealed classsingleton{PrivateSingleton () {} Public StaticSingleton Instance {Get{returnnested.instance;} }            Private classNested {//Explicit Static constructor to tell C # compiler//Not to mark type as BeforeFieldInit        StaticNested () {}Internal Static ReadOnlySingleton instance =NewSingleton (); }}

7. Using. NET 4 ' sLazy<T> 类型

 Public Sealed class singleton{    privatestaticreadonly lazy<singleton> Lazy =        New  New  Singleton ());          Public Static Get return lazy. Value; }}    private  Singleton ()    {    }}

C # Singleton 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.