C # Design pattern (1)--Singleton mode (Singleton)

Source: Internet
Author: User

The singleton pattern is that the so-called class can have only one instance, that is, the class can only be in an internal instance once, and then provide this instance, and the external cannot instantiate the class.

The characteristics of the singleton mode:

1, there can only be one instance;

2, can only create their own unique instance;

3. This instance must be provided to all other objects.

Normal singleton mode (no thread safety is considered)

 // <summary>    ///single-case mode/// </summary>     Public classSingleton {Private StaticSingleton Singleton; PrivateSingleton () {}/// <summary>        ///get instance-thread non-secure mode/// </summary>        /// <returns></returns>         Public StaticSingleton Getsingleton () {if(Singleton = =NULL) Singleton=NewSingleton (); returnSingleton; }     }

Consider multithreading security

     /// <summary>    ///single-case mode/// </summary>     Public classSingleton {Private Static Objectobj =New Object(); Private StaticSingleton Singleton; PrivateSingleton () {}/// <summary>        ///Get instance-thread safety/// </summary>        /// <returns></returns>         Public StaticSingleton Getthreadsafesingleton () {if(Singleton = =NULL)            {                Lock(obj) {singleton=NewSingleton (); }            }            returnSingleton; }    }

C # Design pattern (1)--Singleton mode (Singleton)

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.