C#中几种单例模式

2021-05-31 18:02

阅读:445

标签:HERE   sum   creat   span   ado   create   stat   ted   私有化   

1.静态代码块

/// 
    /// 静态代码块
    /// 仅在第一次调用类的任何成员时自动执行
    /// 
    public class SingletonStatic
    {
        private static readonly SingletonStatic _instance =null;
        static SingletonStatic()
        {
            _instance = new SingletonStatic();
        }
        private SingletonStatic()
        {

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

    }

2.内部类

   /// 
    /// 内部类
    /// 
    public class SingletonInner
    {
        private SingletonInner()
        {

        }
        public static SingletonInner Instance
        {
            get{ return InnerClass.inner; }
        }
        private class InnerClass
        {
            internal static readonly SingletonInner inner = new SingletonInner();
        }
    }

3.Lazy

    /// 
    /// Lazy单例
    /// 
    public class SingletonLazy
    {
        private static readonly SingletonLazy _instance = new Lazy().Value;
        private SingletonLazy()
        {

        }
        public SingletonLazy Instance
        {
            get { return _instance; }
        }

    }

4.单例模式基类(转自https://www.cnblogs.com/zhouzl/archive/2019/04/11/10687909.html)

/// 
    /// https://www.cnblogs.com/zhouzl/archive/2019/04/11/10687909.html
    /// 
    /// 
    public abstract class Singletonwhere T : class
    {
        // 这里采用实现5的方案,实际可采用上述任意一种方案
        class Nested
        {
            // 创建模板类实例,参数2设为true表示支持私有构造函数
            internal static readonly T instance = Activator.CreateInstance(typeof(T), true) as T;
        }
        private static T instance = null;
        public static T Instance { get { return Nested.instance; } }
    }
    class TestSingleton : Singleton
    {
        // 将构造函数私有化,防止外部通过new创建
        private TestSingleton() { }
    }

 

C#中几种单例模式

标签:HERE   sum   creat   span   ado   create   stat   ted   私有化   

原文地址:https://www.cnblogs.com/NNYang/p/11013533.html


评论


亲,登录后才可以留言!