码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式 - 线程安全的单例模式(C#)

时间:2014-11-25 14:29:50      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:线程安全的单例模式   c#   

1、饿汉式单例模式

// 饿汉式单例模式 - by Chimomo
namespace CSharpLearning
{
    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();
        private Singleton() { }

        public static Singleton Instance
        {
            get { return instance; }
        }
    }
}

2、懒汉式单例模式

2.1、借助内部类

// 懒汉式单例模式:借助内部类 - by Chimomo
namespace CSharpLearning
{
    public sealed class Singleton
    {
        private Singleton() { }

        private static class SingletonHolder
        {
            public static readonly Singleton instance = new Singleton();
        }
        public static Singleton Instance
        {
            get { return SingletonHolder.instance; }
        }
    }
}
2.2、普通加锁

// 懒汉式单例模式:普通加锁 - by Chimomo
namespace CSharpLearning
{
    public sealed class Singleton
    {
        private static volatile Singleton instance;
        private static readonly object syncRoot = new object();
        private Singleton() { }
        public static Singleton Instance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
                return instance;
            }
        }
    }
}
2.3、双重检测加锁

// 懒汉式单例模式:双重检测加锁 - by Chimomo
namespace CSharpLearning
{
    public sealed class Singleton
    {
        private static volatile Singleton instance;
        private static readonly object syncRoot = new object();
        private Singleton() { }
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                        }
                    }
                }
                return instance;
            }
        }
    }
}

设计模式 - 线程安全的单例模式(C#)

标签:线程安全的单例模式   c#   

原文地址:http://blog.csdn.net/troubleshooter/article/details/41480349

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