zoukankan      html  css  js  c++  java
  • Singleton设计模式活学活用: 请求单一 vs 线程单一

    /// <summary>
        /// 在Web Request期间只存在唯一实例的类
        /// 使用了Lazy
        /// </summary>
        public class SingletonPerRequest
        {
            public object Data;
    
            public static readonly string Key = "SingletonPerRequest.Key";
    
            public static SingletonPerRequest Current
            {
                get
                {
                    SingletonPerRequest instance = (SingletonPerRequest)HttpContext.Current.Items[Key];
                    if (instance==null)
                    {
                        instance = new SingletonPerRequest();
                        HttpContext.Current.Items[Key] = instance;
                    }
                    return instance;
                }
            }
        }
    
        /// <summary>
        /// 在一个执行线程中只存在唯一实例的类
        /// 使用了Lazy
        /// </summary>
        public class SingletonPerThread
        {
            public object Data;
    
            public static readonly string Key = "SingletonPerThread.Key";
    
            public static SingletonPerThread Current
            {
                get
                {
                    SingletonPerThread instance = (SingletonPerThread)CallContext.GetData(Key);
                    if (instance == null)
                    {
                        instance = new SingletonPerThread();
                        CallContext.SetData(Key, instance);
                    }
                    return instance;
                }
            }
        }

    这只是个示例,你可以将它改为泛型类,以编写更安全的代码.

    此外,CallContext在Web/Win中,可以移植,所以Web中也建议使用第二种方案.

  • 相关阅读:
    springboot之热部署
    在动态sql的使用where时,if标签判断中,如果实体类中的某一个属性是String类型,那么就可以这样来判断连接语句:
    对集合进行判空的操作
    配置logback日志管理的时候
    SpringBoot序列化时间类型的问题
    Cannot determine embedded database driver class for database type NONE
    idea的基础设置
    使用navicat创建数据库
    LESS
    数据库链接池--简单的理解
  • 原文地址:https://www.cnblogs.com/rockniu/p/1601020.html
Copyright © 2011-2022 走看看