简体   繁体   English

MVP中View和Presenter之间的通信模式是什么?

[英]What are the patterns in communication between View and Presenter in MVP?

Reading about MVP pattern I found there are two communication patterns between View and Presenter: 阅读MVP模式我发现View和Presenter之间有两种通信模式:

  • View doesn't know Presenter but provides UI controls implementing HasClickHandler interface where Presenter registers its event handlers. View不知道Presenter,但提供了实现HasClickHandler接口的UI控件,其中Presenter注册其事件处理程序。

  • View knows Presenter , particularly it knows handler method names in Presenter, eg, when a Submit button is clicked in View, a view calls a onSubmitButtonClicked() public method in Presenter. View知道Presenter ,特别是它知道Presenter中的处理程序方法名称,例如,当在View中单击Submit按钮时,视图在Presenter中调用onSubmitButtonClicked()公共方法。

I found the latter to be easier for JUnit testing, because I can directly simulate submitting event to Presenter. 我发现后者更容易进行JUnit测试,因为我可以直接模拟向Presenter提交事件。 However, my understanding was that the View should not know about the Presenter. 但是,我的理解是View不应该知道Presenter。

The third approach to resolve the trade-off is to let the Presenter registers event handlers in the View's controls, where the handlers calls public Presenter methods: 解决权衡的第三种方法是让Presenter在View的控件中注册事件处理程序,处理程序调用公共Presenter方法:

public void bind() {
  display.getSubmitButton().addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
      onSubmitButtonClicked();              
    }
  });
}

But this introduces a lot of boilerplate code. 但是这引入了许多样板代码。

What is the right pattern for View-Presenter communication? View-Presenter通信的正确模式是什么?

I'm still trying to learn this stuff myself, but the way I'm thinking about it now is something like this: 我自己还在尝试学习这些东西,但我现在想的方式是这样的:

public interface View {
    void registerMouseListener(MouseListener listener);
}

public class ViewImpl implements View {
    SomeComponent component; // SomeComponent extends java.awt.Component

    public void registerMouseListener(MouseListener listener) {
        component.addMouseListener(listener);
    }
}

Then you can let the Presenter decide however it wants to register for these events, by adding anonymous listeners, or extending MouseListener itself, etc. 然后你可以让Presenter决定注册这些事件,添加匿名监听器,或者扩展MouseListener本身等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM