码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-24 23:02:43      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   for   re   c   代码   ar   new   .net   

传统的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被拿来用了,才会实例化

浅谈单例的三种实现--C#,布布扣,bubuko.com

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

标签:style   for   re   c   代码   ar   new   .net   

原文地址:http://blog.csdn.net/lan_liang/article/details/38095129

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!