Question

I have the following simple code of Presenter and View (MVP). I am not able to understand that, we just pass the view (i.e "this") in the view constructor to the presenter instance. But, in the presenter class, we have an interface as the parameter. I notice that, we implement the interface in the View. However, I don't understand how we are able to pass class (view instance using "this") when the parameter it accepts is an interface inside Presenter class constructor.

Please explain. I am kind of new.

interface IApplicationConnection
{
   string Connect { get; set;}
   void SetText(string text);
}

public partial class MyForm : Form, IApplicationConnection
{
  private Presenter _presenter;

  public MyForm()
  {
    InitializeComponent();
    _presenter = new Presenter(this);
  }

  public string Connect { get; set; }
}

Presenter Class:

public class Presenter
{
  IApplicationConnection _view;
  public Presenter(IApplicationConnection view)
  {
     _view = view;
  }

  public void Clicked()
  {
    _view.SetText("Clicked");
  }
}
Was it helpful?

Solution

From what you write, it seems that you are unsure on what "this" means. Actually, when in an instance (not static!) method, "this" always refers to the instance the method belongs to and is executed for.

In your example, "this" refers to MyView instance. Since the class implements your interface, you can pass it to the presenter constructor.

Suppose your class implements three interfaces:

public class A : I1, I2, I3 ...

and you are to pass it to

public void Foo( I1, I2, I3 )

then it would be legal to call Foo from within the class as

Foo( this, this, this )

Since the class implements multiple interfaces, it can "pose" as three different specifications expressed as interfaces.

OTHER TIPS

this is an instance of that class

MVP does some separation of concern and you can easily test the presenter with mocked views since you're injecting it through an interface.

You're able to pass the instance of class because the class must implement the interface which is being passed as argument in your presenter.

This is called the dependency injection via constructor. This way it makes the design decoupled because presenter doesn't have to worry or know about the implementation of interface IApplicationConnection_view. It just know that what ever is coming have the functionality implemented.

Also this way MVP pattern becomes more testable as you can mock the view with fake object and test your presenter in Unit tests. I hope this all make sense to you.

This is just how interfaces work. You can pass instance of a class to any method that accepts either

  • this exact class
  • any of its base classes
  • any interfaces implemented by the class.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top