简体   繁体   中英

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:

  • View doesn't know Presenter but provides UI controls implementing HasClickHandler interface where Presenter registers its event handlers.

  • 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.

I found the latter to be easier for JUnit testing, because I can directly simulate submitting event to Presenter. However, my understanding was that the View should not know about the 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:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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