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();
  • 相关阅读:
    Xcode7下模拟器输入文本无法显示系统键盘的解决办法
    Mac系统下开启和关闭隐藏文件的方法
    iOS常用第三方开源框架和优秀开发者博客等
    UILabel 的一个蛋疼问题
    学习进度条
    学习进度条
    四则运算2
    学习进度条
    第一次被要求连接数据库的课堂测试
    课后作业06多态与接口
  • 原文地址:https://www.cnblogs.com/VectorZhang/p/5366812.html
Copyright © 2011-2022 走看看