![](/img/trans.png)
[英]In MVP can the presenter access a user control directly instead via interface?
[英]Why using interface for Presenter in MVP?
我将使用Professional ASP.NET Design Patterns学习MVP 模式 。 在表示层章节中,它学习如何将MVP应用于asp.net。 演示者的代码是:
public class HomePagePresenter : IHomePagePresenter
{
private IHomeView _view;
private ProductService _productService;
public HomePagePresenter(IHomeView view, ProductService productService)
{
_productService = productService;
_view = view;
}
public void Display()
{
_view.TopSellingProduct = _productService.GetBestSellingProducts();
_view.CategoryList = _productService.GetAllCategories();
}
}
public interface IHomePagePresenter
{
void Display();
}
作者说:
我已经定义了这个(HomePagePresenter的接口)来松散地耦合代码并帮助测试。
我无法理解他将如何使用presenter界面创建测试? 当我查看nmock示例时,他们也没有为演示者创建任何界面。
使用接口公开Presenters有很多原因:
多态性 - 您可以使用多个IHomePagePresenter
实现,并可以使用本地上下文依赖注入解析来确定在运行时使用哪个。
在测试期间进行模拟 - 您可能需要模拟此特定的Presenter以进行单元测试,并且对于接口创建模拟比使用具体类更容易。 这实际上也属于多态性,但它是一个具体的现实世界的例子和松散耦合。 “松散耦合”基本上能够快速轻松地交换类的实现,而无需更改太多/任何代码。 测试场景是您正在测试一个Presenter类,它可能引用另一个Presenter接口 - 您将模拟其他Presenter对象而不是使用具体类。
方法/属性访问限制 - 接口限制您可以查看/使用的实现的哪些部分,因此,例如,如果HomePagePresenter
有许多方法/ proeprties,该类的常规使用者不应该使用/有权访问,您可以限制什么他们可以通过使用界面暴露类来使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.