您的位置:首页 > 其它

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中也建议使用第二种方案.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: