Three implementations of Singleton -- C #

Source: Internet
Author: User

Three implementations of Singleton -- C #
Traditional double check:


public sealed class Singleton{    private static Singleton instance = null;    private static readonly object padlock = new object();    Singleton()    {    }    public static Singleton Instance    {        get        {            if (instance == null)            {                lock (padlock)                {                    if (instance == null)                    {                        instance = new Singleton();                    }                }            }            return instance;        }    }}


Defects:
1. The code is bloated.
2. The performance of double check is slightly lower (compared with the subsequent implementation version)




Version that utilizes the. net framework static feature:
public sealed class Singleton{    public static readonly Singleton instance = new Singleton();    private Singleton()    {    }}


1. How to ensure the safety of singleton and thread?
Because the static instance only has one memory in the AppDomain
2. defects?
The static constructor is executed before the field, without lazy (the instance is used only)


Lazy version
public sealed class Singleton{    public static readonly Singleton instance = new Singleton();    // Explicit static constructor to tell C# compiler    // not to mark type as beforefieldinit    static Singleton()    {    }    private Singleton()    {    }}


Improvements:
Display the declared static constructor and tell the compiler to execute it after the field. This will be instantiated only when the field is used.

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.