C#中幾種單例模式

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() { }
    }
相關文章
相關標籤/搜索