Singleton mode note

Source: Internet
Author: User

The Singleton mode in C #: (from the book "big talk design model-Cheng Jie)

Singleton ):

Ensure that a class has only one instance and provides a global access point to it.

Generally, we can make a global variable accessible to an object, but it cannot prevent you from instantiating multiple objects. The best way is to let the class itself be responsible for saving its unique instance. This class can ensure that no other instance can be created, and it can provide a method to access the instance.

Example:

class Singleton    {        private static Singleton instance;        private Singleton()        {                     }        public static Singleton GetInstance()        {            if (instance == null)            {                instance = new Singleton();            }            return instance;        }        /// <summary>        /// Client side code        /// </summary>        /// <param name="args"></param>        static void Main(string[] args)        {            Singleton s1 = Singleton.GetInstance();            Singleton s2 = Singleton.GetInstance();            if (s1 == s2)            {                Console.WriteLine(  "They have same instance!");            }            Console.Read();        }    }
View code

Execution result:

Singleton encapsulates his unique instance, so that he can strictly control the user's access to him and access him as appropriate. Simply put, he can control access to the only instance!

 

Singleton mode for multithreading:

Meaning: Lock is to ensure that when a thread is located in the critical section of the Code, the other thread does not enter the critical section. If other threads attempt to enter the locked code. Then, it waits until the object is released.

Example:

class Singleton    {        private static Singleton instance;        private static readonly object syncRoot = new object();        private Singleton()        {                     }        public static Singleton GetInstance()        {            lock (syncRoot)            {                if (instance == null)                {                    instance = new Singleton();                }            }            return instance;        }        /// <summary>        /// Client side code        /// </summary>        /// <param name="args"></param>        static void Main(string[] args)        {            Singleton s1 = Singleton.GetInstance();            Singleton s2 = Singleton.GetInstance();            if (s1 == s2)            {                Console.WriteLine(  "They have same instance!");            }            Console.Read();        }    }
View code

The execution result is the same as above.
Note: The use of Singleton mode in this multi-thread mode will affect the performance. The "Double Lock" is improved as follows ":

class Singleton    {        private static Singleton instance;        private static readonly object syncRoot = new object();        private Singleton()        {                     }        public static Singleton GetInstance()        {            if (instance == null)            {                lock (syncRoot)                {                     if(instance==null)                    {                        instance = new Singleton();                    }                }            }            return instance;        }    }
View code

The preceding Singleton mode is "lazy Singleton type"
The following is the "Hungry Chinese Singleton class ":

Static initialization of the "Hungry Chinese Singleton mode ":

C # And the Common Language Runtime Library also provide a "static initialization" method, which does not require developers to explicitly write thread security code, this will solve the problem of being insecure in a multi-threaded environment.

Example:

Public sealed class Singleton // sealed prevents derivation, and the derivation may add an instance {// create an instance when any member of the class is referenced for the first time. The public Language Runtime Library is responsible for processing variable initialization Private Static readonly Singleton instance = new Singleton (); Private Singleton () {} public static Singleton getinstance () {return instance ;} static void main (string [] ARGs) {Singleton S1 = Singleton. instance; Singleton S2 = Singleton. getinstance (); If (S1 = S2) {console. writeline ("they have same instance! ") ;}Console. Read ();}}
View code

Execution result:

Note: The instance variable is marked as readonly, which means that variables can only be allocated during static initialization or in the class constructor.
Because this static initialization method instantiates itself when it is loaded, it is called a hungry Singleton class in the image, the Processing Method of the original Singleton mode is to instantiate itself when it is referenced for the first time, so it is called a lazy Singleton class.

 

Singleton mode note

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.