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

  • 相关阅读:
    Http record java
    Java String constructed from byte array has bad length
    Schema
    Scale-up(纵向扩展) vs Scale-out(横向扩展)
    数据同步
    JDBC and Oracle conn.commit and conn.setAutocommit not working properly
    DGIM
    Github Blog 搭建手册
    软件探索(一)
    经典书单 —— 人文社科
  • 原文地址:https://www.cnblogs.com/zhengzc/p/11216236.html
Copyright © 2011-2022 走看看