首页 > 代码库 > 浅谈单例的三种实现--C#

浅谈单例的三种实现--C#

传统的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;
        }
    }
}


缺陷:
1.代码很臃肿
2.double check性能稍微差一些(比起后面的实现版本)




利用.net framework static特性的版本版:
public sealed class Singleton
{
    public static readonly Singleton instance = new Singleton();


    private Singleton()
    {
    }
}


1.如何保证单例和线程安全?
因为静态实例在AppDomain里面只有一份内存
2.缺陷?
静态构造函数在field之前执行,没有lazy(只有用的时候才实例)


lazy版本
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()
    {
    }


}


改进的地方:
显示声明静态构造函数,告诉编译器,在field之后执行,这样就只有field被拿来用了,才会实例化