Singleton设计模式活学活用: 请求单一 vs 线程单一
2009-11-11 15:26
411 查看
/// <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; } } }
.codearea{ color:black; background-color:white; line-height:18px; border:1px solid #4f81bd; margin:0; width:auto !important; width:100%; overflow:auto; text-align:left; font-size:12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono", courier,monospace,serif}
.codearea pre{ color:black; line-height:18px; padding:0 0 0 12px !important; margin:0em; background-color:#fff !important}
.linewrap pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; word-break:normal}
.codearea pre.alt{ background-color:#f7f7ff !important}
.codearea .lnum{color:#4f81bd;line-height:18px}
这只是个示例,你可以将它改为泛型类,以编写更安全的代码.
此外,CallContext在Web/Win中,可以移植,所以Web中也建议使用第二种方案.
相关文章推荐
- C++设计模式--单一对象模式<Singleton>
- 单一设计模式(Singleton)
- 设计一个线程安全的单例(Singleton)模式
- JAVA设计模式-单例模式(Singleton)线程安全与效率
- 设计一个线程安全的单例(Singleton)模式
- C++设计模式之Singleton(单件/单例)模式
- 设计模式——单例模式(Singleton )
- 【工作中学习1】两个设计模式:Singleton(单例)和 Adapter(适配器)
- 转:设计模式Singleton(例子是C#的)
- iOS开发之旅--深入讲解Singleton(单例设计模式)
- 设计模式六大原则(1):单一职责原则
- 设计模式-单件模式(Singleton)
- 设计模式学习(一)—— 四要素以及Singleton
- Java设计模式透析之 —— 单例(Singleton)
- C++设计模式之五:SINGLETON(单件模式)
- Java设计模式- Singleton(单例模式)
- (3)Java设计模式-单例模式(Singleton)
- java 设计模式六大原则(1):单一职责原则
- 设计模式实践——单一职责原则SRP
- 活用设计模式