为什么在MVP中使用Presenter接口?

5

我将学习使用《专业ASP.NET设计模式》来学习MVP模式。在演示层章节中,它介绍了如何将MVP应用于asp.net。Presenter的代码如下:

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示例时,他们也没有为presenter创建任何接口。


提供源代码进行练习,同时包含单元测试以解释其好处 - http://www.advertisingmarket.co.uk/MVPPattern - Julius Depulla
1个回答

3

将你的Presenters使用接口暴露出来有很多好处:

  1. 多态性 - 你可以有几个IHomePagePresenter的实现,并使用本地上下文依赖注入解析来确定在运行时使用哪一个。

  2. 测试中的模拟 - 你可能需要为单元测试目的模拟这个特定的Presenter,使用接口创建Mock比使用具体类更容易。这也属于多态性和松散耦合的例子。"松散耦合"基本上是能够快速轻松地交换类的实现而无需更改任何代码。测试场景是你正在测试一个Presenter类,它可能引用另一个Presenter接口 - 你会模拟另一个Presenter对象而不是使用具体类。

  3. 方法/属性访问限制 - 接口限制了你可以看到/使用的实现的哪些部分,所以如果HomePagePresenter有许多常规消费者不应该使用/访问的方法/属性,你可以通过使用接口暴露类来限制他们可以使用的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接