[英]Why using interface for Presenter in MVP?
I am going to learn MVP pattern using Professional ASP.NET Design Patterns . 我将使用Professional ASP.NET Design Patterns学习MVP 模式 。 In presentation layer chapter it learn how to apply MVP to asp.net.
在表示层章节中,它学习如何将MVP应用于asp.net。 The code for presenter is:
演示者的代码是:
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();
}
The author said: 作者说:
I have defined this (interface for HomePagePresenter) to loosely couple the code and to aid testing.
我已经定义了这个(HomePagePresenter的接口)来松散地耦合代码并帮助测试。
I can not understand how he will use presenter interface for creating tests? 我无法理解他将如何使用presenter界面创建测试? When I looked at nmock example they also does not created any interface for presenter.
当我查看nmock示例时,他们也没有为演示者创建任何界面。
There are a number of reasons to expose your Presenters using interfaces: 使用接口公开Presenters有很多原因:
Polymorphism - you could have several IHomePagePresenter
implementation and may use local context dependency injection resolution to determine which one to use at runtime. 多态性 - 您可以使用多个
IHomePagePresenter
实现,并可以使用本地上下文依赖注入解析来确定在运行时使用哪个。
Mocking during testing - you could need to mock this particular Presenter for unit testing purposes and it's way easier to create a Mock against an interface than work with a concrete class. 在测试期间进行模拟 - 您可能需要模拟此特定的Presenter以进行单元测试,并且对于接口创建模拟比使用具体类更容易。 This really falls under polymorphism as well, but it's a concrete real-world example and loose-coupling.
这实际上也属于多态性,但它是一个具体的现实世界的例子和松散耦合。 "Loose coupling" is basically being able to swap out the implementation of a class quickly and easily without having to change much/any code.
“松散耦合”基本上能够快速轻松地交换类的实现,而无需更改太多/任何代码。 The test scenario is that you are testing a Presenter class which may have a reference to another Presenter interface - you would mock the other Presenter object instead of using a concrete class.
测试场景是您正在测试一个Presenter类,它可能引用另一个Presenter接口 - 您将模拟其他Presenter对象而不是使用具体类。
Method/property access restrictions - Interfaces restrict what parts of an implementation you can see/use, so for example if HomePagePresenter
had a number of methods/proeprties that regular consumers of the class shouldn't use/have access to, you can restrict what they can use by exposing the class using the interface instead. 方法/属性访问限制 - 接口限制您可以查看/使用的实现的哪些部分,因此,例如,如果
HomePagePresenter
有许多方法/ proeprties,该类的常规使用者不应该使用/有权访问,您可以限制什么他们可以通过使用界面暴露类来使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.