Several simple implementations of the C # Singleton pattern

Source: Internet
Author: User

What is a singleton mode?

Here I do not do too much explanation, after all, the information about Singleton is too much. Click here

1. The simple idea is that the action of creating an object singleton shifts to another behavior, using a behavior to create the object itself, as follows:

   public class Singleton    {        private static Singleton _singleton = null;        public static Singleton CreateInstance ()        {            if (_singleton = = null)            {
Console.WriteLine ("Created"); _singleton = new Singleton (); } return _singleton; } }

This seems to be no problem, but there is no such possibility, while two actions are judged that the object is empty, then this object will be created 2 times? Yes, in multi-threading, this is not guaranteed for single cases.

Just like this, when you create multiple threads to create this object instance, it is created several times, this time, to improve the code.

    public class Singleton    {        private static Singleton _singleton = null;        private static Object Singleton_lock = new Object (); Lock sync public        static Singleton CreateInstance ()        {                lock (Singleton_lock)                {
Console.WriteLine ("Passing Through"); if (_singleton = = null) {
Console.WriteLine ("Created"); _singleton = new Singleton (); } } return _singleton; } }

Debug code:

               TaskFactory TaskFactory = new TaskFactory ();                list<task> taskList = new list<task> ();                for (int i = 0; i < 5; i++)                {                    tasklist.add (taskfactory.startnew () =                     {                         Singleton Singleton = Si Ngleton. CreateInstance ();                      }));                }

Results:

Above, we create multiple threads, and at the same time to create an instance of this object, in the second time, the object name has been created, although only once created to meet our needs, but we know that the object is created, but also need to come in to do unnecessary action?

We all know that the synchronous lock in order to achieve the desired effect, but also the loss of performance, then the output below, is obviously not necessary action, so we optimize it.

    public class Singleton    {        private static Singleton _singleton = null;        private static Object Singleton_lock = new Object ();        public static Singleton CreateInstance ()        {            if (_singleton = = null)//double if +lock
{ Lock (Singleton_lock) { Console.WriteLine ("Passing through. "); if (_singleton = = null) { Console.WriteLine ("is created. "); _singleton = new Singleton ();}} } return _singleton; } }

Results:

Obviously, this achieves our expectation that after the object has been created, there is no need to do any extra action.

Using static variables to implement Singleton mode

    public class Singletonthird {//<summary>///        static variable
</summary> private static Singletonthird _singletonthird = new Singletonthird (); public static Singletonthird CreateInstance () { return _singletonthird; } }

Does it feel elegant to use static variables to implement a singleton, guaranteed by the CLR, to be called before the program first uses the class, and to call only once

PS: But his shortcomings are also obvious, after the initialization of the program, the static object is constructed by the CLR, even if you are useless.

Implementing a singleton pattern with static constructors

    public class Singletonsecond    {        private static singletonsecond _singletonsecond = null;        Static Singletonsecond ()        {
_singletonsecond = new Singletonsecond (); } public static Singletonsecond CreateInstance () { return _singletonsecond; } }

Static constructors: Only one, no parameter, cannot be called by the program.

It is also guaranteed by the CLR that it is called before the program first uses the class, and it is called only once

As with static variables, it will be instantiated as the program runs, with a static variable.

Several simple implementations of the C # 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.