C # Singleton mode (Singleton pattern)

Source: Internet
Author: User

(Beginners write a blog, mainly on their own study of the summary.) Will explain a lot of small details. )

Definition of a singleton pattern:

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

First of all, it should be understood that the process of generating objects is simply a string s=new string (), then S is an instance.

Q: How can I generate only one instance?

A:1) The constructor must first be private to prevent other classes from being instantiated, and there can be only one constructor. Because the system defaults to an parameterless constructor, and the default public access modifier. So you have to write a private non-argument to invalidate the default. (usually singleton mode is not with formal parameters)

2) Declare a static instance of itself in the class, and then return it through a static method.

Q: How do I provide a global access point?

A: Create a public and static property in the class. (Because a static method is a member method in a class, it belongs to the entire class, that is, you can call it directly without creating any objects.) Singleton mode is not allowed for other class instances. )

Code:

It is divided into two modes:

1.LAZY mode

Is deferred loading, the design pattern is to avoid some unnecessary performance overhead, the so-called lazy load is when the real need for data (read the value of the property), only to actually perform the data load operation. Using it effectively can greatly improve system performance.

2. A Hungry man mode

In contrast to the lazy mode, the load will instantiate itself. Easiest single-case mode.

Analysis Code 1: (Classic)

1 //don't use this way.
2 Public Sealed classSingleton3 {4 Private StaticSingleton instance=NULL;//declaring a static instance of itself5 PrivateSingleton () {}//Private Construction6 Public StaticSingleton Instance//provide a global access point7 {8 if(instance==NULL)//The instance does not exist to create9 {TenInstance =NewSingleton (); One } A returninstance; - } -}

The code is for understanding only, and the definition of singleton pattern.

Issue: This method is non-thread-safe and creates an instance if instance is null when there are two threads entering at the same time. In fact, the instance could have been created before the test, but the memory model does not guarantee that the instance can be seen by other threads.

Below we optimize the improvement

Analysis Code 2: (Non-thread thread)

 Public Sealed classsingleton{Private StaticSingleton instance =NULL; Private Static ReadOnly Objectpadlock =New Object();//define an identity to ensure thread synchronizationSingleton () {} Public StaticSingleton Instance {Lock(padlock)//Unlocked When a thread arrives and unlocks when it encounters a lock thread that hangs and waits to be unlocked            {                if(Instance = =NULL) {instance=NewSingleton (); }                returninstance; }    }}

The above solves the multithreading problem.

Problem: In terms of performance, the lock becomes a must every time when the instance is responding. At this point there is no need to lock the thread helper object after the decision, so the above implementation method adds additional overhead.

Below we make the optimization improvements:

Code Analysis 3: (Dual Lock)

1  Public Sealed classSingleton2 {3     Private StaticSingleton instance =NULL;4     Private Static ReadOnly Objectpadlock =New Object();5 Singleton () {}6      Public StaticSingleton Instance7     {8         Get9         {Ten             if(Instance = =NULL)//The outer if statement block, which allows each thread to acquire an instance without having to lock each time, because only the instance is empty (that is, an instance needs to be created), the lock creation is required One             { A                 Lock(padlock) -                 { -                     if(Instance = =NULL) the                     { -Instance =NewSingleton (); -                     } -                 } +             } -             returninstance; +         } A     } at}

This "double check lock" theory is perfect.

The problem is: there is no guarantee that it will run smoothly on a single-processor or multiprocessor computer. (There is a problem anyway, then read it again and see what's going On)

Code Analysis 4: (not full lazy)

1  Public Sealed classSingleton2 {3     Private Static ReadOnlySingleton instance =NewSingleton ();4 5     //the static constructor that is displayed6     //Static constructors Suppress the BeforeFieldInit attribute (execute a static function before accessing the member)7     StaticSingleton () {}8     PrivateSingleton () {}9      Public StaticSingleton InstanceTen     { One         Get A         { -             returninstance; -         } the     } -}

Incomplete lazy mode (does not play too much effect by suppressing the Beforefildinit feature)

Code Analysis 5: (Full lazy)

1  Public Sealed classSingleton2 {3     PrivateSingleton () {}4      Public StaticSingleton Instance {Get{returnnested.instance;}} 5 //Nested Classes6     Private classNested7     {8        //Suppress beforefieldinit characteristics9         StaticNested () {}Ten         Internal Static ReadOnlySingleton instance =NewSingleton (); One     } A}

Nested classes are used here (nested types are lazy loaded, meaning nested types are initialized when they are used)

Code Analysis 6: (lazy<t>)

1  Public Sealed classSingleton2 {3 //use. NET4 lazy<t>4     Private Static ReadOnlyLazy<singleton> lazy =NewLazy<singleton> (() =NewSingleton ());5      Public StaticSingleton Instance {Get{returnlazy. Value; } }6     PrivateSingleton () {}7}

Lazy<t> object initialization is thread-safe by default, in a multithreaded environment, the first thread that accesses the Value property of the Lazy<t> object initializes the Lazy<t> object, and the thread that is accessed later will use the data that was initialized for the first time.

All of the above are in the lazy mode, now understand the next a hungry man mode

Code Analysis 7:

 Public Sealed class singleton{        privatestaticreadonly Singleton instance=New Singleton (); // Direct instantiation        Private Singleton () {}          Public Static Singleton Instance ()        {               return  instance;        }}

In this mode, there is no need to solve the thread safety problem yourself, the CLR will fix it for us. As a result of this class being loaded, the class is automatically instantiated without having to instantiate a unique singleton object after the first call to instance ().

In order to optimize the system, the optimization mode is chosen. The best of the lazy mode should be to use lazy<t> short security.

All of these are my summary of the single-case pattern learning in the blog park. In the future, some specific projects will be added to make it easier for beginners like me to absorb understanding and eventually reach extrapolate. Here the focus of reference to the article here, I hope that we have a lot of advice on the place to raise points. Thank.

C # Singleton mode (Singleton pattern)

Related Article

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.