首页 > Windows开发 > 详细

C# 单例模式实现

时间:2019-07-20 09:18:31      阅读:87      评论:0      收藏:0      [点我收藏+]

Double-Checked Locking

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

静态初始化

    public sealed class Singleton
    {
        private static readonly Singleton _instance = new Singleton();

        // 显示静态构造函数,告诉C#编译器不要将Type标记beforefieldinit(这样就能够使程序在类的字段被引用时才会实例化)
        static Singleton() { }

        // 防止创建该类的默认实例
        private Singleton() { }

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

延迟初始化

    public sealed class Singleton
    {
        private Singleton() { }

        public static Singleton Instance { get { return Nested._instance; } }

        private class Nested
        {
            static Nested() { }
            internal static readonly Singleton _instance = new Singleton();
        }
    }

.Net 4‘s Lazy<T> type 

    public sealed class Singleton
    {
        private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
        private Singleton() { }
        public static Singleton Instance { get { return lazy.Value; } }
    }

以上4中方式都是线程安全的单例实现代码,推荐使用Lazy<T>的方式简单且性能良好。

C# 单例模式实现

原文:https://www.cnblogs.com/zhengzc/p/11216236.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!