码迷,mamicode.com
首页 > Windows程序 > 详细

C#单例模式的三种写法

时间:2017-06-13 21:09:15      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:help   otto   class   mil   margin   mod   top   volatile   family   

第一种……

public class Singleton
{
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)

        {
            _instance = new Singleton();
        }
        return _instance;
    }
}

另外一种

public class Singleton
{
    private volatile static Singleton _instance = null;
    private static readonly object lockHelper = new object();
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            lock(lockHelper)
            {
                if(_instance == null)
                     _instance = new Singleton();
            }
        }
        return _instance;
    }
}

第三种

public class Singleton
{

    private Singleton(){}
    public static readonly Singleton instance = new Singleton();
}  

C#单例模式的三种写法

标签:help   otto   class   mil   margin   mod   top   volatile   family   

原文地址:http://www.cnblogs.com/gccbuaa/p/7003456.html

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