您的位置:首页 > 其它

.NET:Microsoft.Practices.ServiceLocation 之 动态单例模式

2013-05-06 12:30 190 查看

背景

框架开发中,经常会用到“单例模式”,但是传统的单例模式不支持多态和运行时变化,在关注测试的今天,这种模式是不可行的。为了应对这种情况,微软又提供了另外一种模式,暂且将其称为“动态单例模式”。 我也想统一我的框架对单例的使用模式,因此就写了这篇文章。

Microsoft.Practices.ServiceLocation 核心代码

看完代码,如何使用这种模式就不用我多介绍了。

IServiceLocator

View Code

namespace Microsoft.Practices.ServiceLocation
{
/// <summary>
/// This class provides the ambient container for this application. If your
/// framework defines such an ambient container, use ServiceLocator.Current
/// to get it.
/// </summary>
public static class ServiceLocator
{
private static ServiceLocatorProvider currentProvider;

/// <summary>
/// The current ambient container.
/// </summary>
public static IServiceLocator Current
{
get { return currentProvider(); }
}

/// <summary>
/// Set the delegate that is used to retrieve the current container.
/// </summary>
/// <param name="newProvider">Delegate that, when called, will return
/// the current ambient container.</param>
public static void SetLocatorProvider(ServiceLocatorProvider newProvider)
{
currentProvider = newProvider;
}
}
}


动态单例模式的优点

支持多态。

运行时可变。

支持其它级别范围的单例,如:请求级、线程级和会话级等。

支持对象池。

备注

Microsoft.Practices.ServiceLocation下载地址:http://commonservicelocator.codeplex.com/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: