码迷,mamicode.com
首页 > Windows程序 > 详细

C#中几种单例模式

时间:2019-06-13 00:42:45      阅读:157      评论:0      收藏:0      [点我收藏+]

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

1.静态代码块

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

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

    }

2.内部类

   /// <summary>
    /// 内部类
    /// </summary>
    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

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

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

    }

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

/// <summary>
    /// https://www.cnblogs.com/zhouzl/archive/2019/04/11/10687909.html
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class Singleton<T> where 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<TestSingleton>
    {
        // 将构造函数私有化,防止外部通过new创建
        private TestSingleton() { }
    }

 

C#中几种单例模式

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

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

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