zoukankan      html  css  js  c++  java
  • C# 单例模式实现

    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>的方式简单且性能良好。

  • 相关阅读:
    js:通过正则匹配获取页面的url中的参数
    BZOJ 4873 寿司餐厅 网络流
    BZOJ 3308 毒瘤结论 网络流
    BZOJ3451 CDOJ1562点分治+FFT
    P3731 二分图匹配必经边
    Hdu 6268 点分治 树上背包 bitset 优化
    Hdu 1517 巴什博奕变形
    dsu on tree
    CF #546 D.E
    HNOI 世界树 虚树
  • 原文地址:https://www.cnblogs.com/zhengzc/p/11216236.html
Copyright © 2011-2022 走看看