zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    AtCoder Grand Contest 005F
    AtCoder Regular Contest 095E
    插头DP--URAL1519Formula 1
    「CodePlus 2018 3 月赛」白金元首与莫斯科
    hdu 5795
    hdu 5800
    HDU5802
    hdu 5787 数位dp,记忆化搜索
    poj 1015
    hdu 3092 (简化的素数打表+dp+log的用法) ps(开数组和预处理时数组要大点处理多一点。。。)
  • 原文地址:https://www.cnblogs.com/VectorZhang/p/5366812.html
Copyright © 2011-2022 走看看