0

I'm trying to develop an Android app following MVP pattern so I can separate the views from the logic of the application.

So let's put an example in order to illustrate my doubts.

public interface IView {

   public void showToast(String text);
}

public class Presenter() {

    View view;

    public presenter(View _view) {

         view = _view;
     }

    public void setCustomToast(String text) {

          view.showToast("hello");
     }
}

public class View implements IView {

    Public void showToast(String text) {
          Toast.makeText(getApplicationContext(), text, LENGTH_LONG).show();
    }
}

Why the interface gives abstraction and allow to separate code? Without the interface wouldn't it work the same?

marianosimone
  • 3,366
  • 26
  • 32
Aldridge1991
  • 1,326
  • 6
  • 24
  • 51
  • This seems more related to OOP than android or mvp. Not sure if I understand your question correctly, but basically the `IView` interface allows you to decouple your `View` implementation, so the `Presenter` doesn't need to know about it. Is there anything in particular there that you are having trouble getting? – marianosimone Mar 29 '18 at 23:24
  • Imagine you wanted to be able to operate on that “View” from a component that has no knowledge of Android (just dream w/me here…), with your interface, you’re stating the required contract by which your `View` will showToasts. The consuming component, unaware of views, knows that there’s this `IView` object, that means nothing more than that, that has a method called `showToast(String)`. It doesn’t need to know anything else. Now you could unit test that `Component.doSomethingThatShouldShowAToast();` calls a `IView.showToast(String)`, w/out any more knowledge. – Martin Marconcini Mar 29 '18 at 23:43
  • But why do you say that it has no knowledge? The class is being passed in the constructor – Aldridge1991 Mar 30 '18 at 06:18

1 Answers1

1

To properly decouple your presenter and view you shouldn't pass an instance of View directly to the presenter, like you did here:

public presenter(View _view) {

         view = _view;
     }

The correct is to pass the interface that the view implements:

public presenter(IView _view) {

         view = _view;
     } 

Therefore decoupling presenter and view. So answering your question, by using interfaces the presenter doesn't need to know who the view actually is, it could be a Fragment, an Activity or a View object. All it knows is about the set of methods available through the interface. The same is valid for the presenter in the view, you normally make the presenter conform with an interface and the view only knows about that interface, not the actuall presenter, once again abstracting the implementation

Levi Moreira
  • 11,917
  • 4
  • 32
  • 46