• NopCommerce中的单例


    项目中经常会遇到单例的情况。大部分的单例代码都差不多像这样定义:

    internal class SingletonOne
        {
            private static SingletonOne _singleton;
    
            private SingletonOne()
            {
            }
    
            public static SingletonOne Instance
            {
                get
                {
                    if (_singleton == null)
                    {
                        var instance = new SingletonOne();
                        Interlocked.CompareExchange(ref _singleton, instance, null);
                    }
    
                    return _singleton;
                }
            }
        }

    但是很明显的一个缺点是这个类只能用作单例。

    最近看了NopCommerce对单例有个包装。觉得有点新颖 给大家分享一下。

    /// <summary>
        /// Provides access to all "singletons" stored by <see cref="Singleton{T}"/>.
        /// </summary>
        public class Singleton
        {
            static Singleton()
            {
                allSingletons = new Dictionary<Type, object>();
            }
    
            static readonly IDictionary<Type, object> allSingletons;
    
            /// <summary>Dictionary of type to singleton instances.</summary>
            public static IDictionary<Type, object> AllSingletons
            {
                get { return allSingletons; }
            }
        }
    public class Singleton<T> : Singleton
        {
            static T instance;
    
            /// <summary>The singleton instance for the specified type T. Only one instance (at the time) of this object for each type of T.</summary>
            public static T Instance
            {
                get { return instance; }
                set
                {
                    instance = value;
                    AllSingletons[typeof(T)] = value;
                }
            }
        }

    比如定义了一个类, 那么可以这样使用

    public class Fake
    {
    }
    
    Singleton<Fake>.Instance = new Fake();
  • 相关阅读:
    斐波纳契数列
    实现刮刮乐的效果
    简易版美图秀秀
    js 宏任务和微任务
    作业3 阅读
    作业2 结对子作业
    做汉堡
    练习一
    Java设计模式十八:代理模式(Proxy)
    Java设计模式二十:适配器模式(Adapter)
  • 原文地址:https://www.cnblogs.com/VectorZhang/p/5366812.html
Copyright © 2020-2023  润新知