C # Design Mode Study Notes-singleton Mode

Source: Internet
Author: User

C # Design Mode Study Notes-singleton Mode
Recently, when I was learning the design mode and the creation mode, I encountered the singleton mode (or Singleton mode). Now I want to take some notes.

The definition in Design Patterns: Elements of Resuable Object-Oriented Software is: Ensure a class only has one instance, and provide a global point of access. Its main feature is not to generate a new instance based on client program calls, but to control the number of instances of a certain type-the only one. (Design model-engineering implementation and expansion based on C #, Wang xiang ). In other words, the singleton mode ensures that the specified class has only one instance at any time during the entire application lifecycle, it also provides a global access point for the customer program to obtain the instance.

I. Classic Mode:

public class Singleton{        private static Singleton instance;        private Singleton()        {                }        public static Singleton GetInstance()        {                if(instance==null)                {                        instance=new Singleton();                }                return instance;        }}

Resolution:

1) First, the Singleton constructor must be private to ensure that the client program will not generate an instance through the new () operation, so as to achieve the Singleton goal;

2) because the lifecycle of static variables is the same as that of the entire application, you can define a Private Static global variable instance to save the unique instance of the class;

3) You must provide a global function to access the instance and provide the function to control the number of instances. That is, you can use the if statement to determine whether the instance has been instantiated, if not, you can create an instance with new (). Otherwise, an instance is directly returned to the customer.

In this classic mode, the problem of concurrent instance acquisition by threads is not taken into account. That is, when two threads obtain instance instances at the same time and the value is null, two threads create instances respectively, the Singleton rule is violated. Therefore, you need to modify the above Code.

Ii. Singleton mode with multiple threads

1. Lazy Mode

public class Singleton{       private static Singleton instance;       private static object _lock=new object();       private Singleton()       {       }       public static Singleton GetInstance()       {               if(instance==null)               {                      lock(_lock)                      {                             if(instance==null)                             {                                     instance=new Singleton();                             }                      }               }               return instance;       }}

The above Code uses the dual lock method to better solve the implementation of the Singleton mode under multiple threads. First look at the if statement block in the inner layer. When this statement block is used, the lock operation is performed first to ensure that only one thread can access this statement block, and then only one instance is created. Look at the if statement block of the outer layer, so that each thread does not have to lock the instance every time it wants to obtain the instance, because the lock is required only when the instance is empty (that is, an instance needs to be created, if an instance already exists, it is returned directly, saving performance overhead.

2. Hunger Mode

This mode is characterized by active instances.

public sealed class Singleton{        private static readonly Singleton instance=new Singleton();         private Singleton()        {        }        public static Singleton GetInstance()        {               return instance;        }}
The preceding readonly key can be used with static to specify that the constant is of class level. Its Initialization is implemented by the static constructor and can be compiled at runtime. In this mode, the CLR will solve the thread security issue for us. It can be seen that this class will be automatically instantiated when it is loaded, instead of generating a unique singleton object after the first call of GetInstance.

 

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.