C # design Pattern Creation class Mode: Singleton mode

Source: Internet
Author: User

Many times in the design process of the program, the system will require a type in an application domain only once, or because of performance considerations, or because of the logic of the requirements, in short, there is such a requirement exists, that in the design pattern has exactly such a pattern can meet such requirements.

Implementing singleton Patterns in C # can be achieved by defining a private constructor, and of course, by defining a static constructor. The reason that a class's static constructor can be used to perform a singleton pattern in singleton mode is that when a static variable is accessed , theCLR invokes the class's static constructor (the type constructor), creating the type object of the static class , The CLR wants to ensure that the type constructor is executed only once per application domain, and in order to do this, when the type constructor is invoked, the CLR adds a mutually exclusive thread synchronization lock for the static class, so that if multiple threads attempt to invoke a static constructor of a type at the same time, Then only one thread can gain access to the static class, and the other threads are blocked. After the first thread finishes executing the type constructor's code and frees the constructor, the other blocked threads are woken up, and then the constructor is found to be executed, so these threads no longer execute the constructor, but simply return from the constructor. If you call these methods again, the CLR will realize that the type constructor has been executed and will not be called. Calling a static method in a class, or accessing a static member variable in a class, is the same as the procedure above, so static members are thread-safe.

Read the above description, it can be seen that static members in the C#runtime special processing, especially suitable for the establishment of a singleton model.

 Public class Singleton    {        publicstaticreadonly  Singleton _instance;         Static Singleton ()        {            _instance=new  Singleton ();        }         Private Singleton ()        {                    }    }

The short line of code above establishes a standard simple interest pattern, in which the private constructor is defined to prevent the use of the new keyword from accessing the constructor outside the class, using the static constructor, which is to initialize the read-only field _instance of this public, global access. From the above explanation, it is also possible to use the CLR-sent mutex for free to execute synchronously and the CLR to ensure that the static constructor is executed only once, that is, the perfect implementation of all the requirements of the singleton pattern. Therefore, this approach is the best choice for both efficiency and brevity, and there is a double-judging way to implement a singleton pattern:

  Public classAnothersingleton {PrivateAnothersingleton () {}Private StaticAnothersingleton _instance; Private  Static ReadOnly Objectpadlock=New Object();  Public StaticAnothersingleton getinstance () {if(_instance==NULL)            {                Lock(PadLock) {if(_instance==NULL) {_instance=NewAnothersingleton (); }                }            }            return_instance; }    }

This code can also be used to create a singleton mode, but because of the use of locks, so the initialization time is slightly longer, but this code implementation of the singleton mode is also suitable for running in a multithreaded environment. The above two examples are the most commonly used best used singleton mode implementation.

Because the singleton mode does not need to consider the specific use environment, as long as the demand, can realize, so this article does not involve the corresponding scene. Let's get here first.

C # design Pattern Creation class Mode: 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.