I have implemented the MVP pattern in a few WinForms applications that uses a passive view. I implement an interface containing properties and delegates in the form of Action< T > and Func< T > to wire up UI events in concrete views and call back to the presenter.
I am about to start a new project and did a little research into the pattern online including the many examples of the pattern here and notice that the all use EventHandler to notify presenters.
I don't really understand why events would be used in this case, since I see a view as only having one presenter.
My question is, is this for the sake of remaining consistent with how the .Net framework uses events, or for some other reason that I am not seeing?
Here is a trivial example of the pattern I use:
public interface IViewAbstraction
{
public ModelData ModelData { set; }
public Action<ModelData> ModelDataChangedCallback { set; }
}
public class SomeWinForm : Form, IViewAbstraction
{
private Action<ModelData> modelDataChanged;
private ModelData model;
public ModelData ModelData
{
set { /* when this property changes, update UI */ }
}
public Action<ModelData> ModelDataChangedCallback
{
set { modelDataChanged = value; }
}
private void OnSomeWinformsEvent(EventArgs args)
{
if (modelDataChanged == null) throw new Exception();
modelDataChanged(model);
}
}
public class Presenter
{
private readonly IViewAbstraction view;
private readonly IDataLayerAbstraction dataLayer;
public Presenter(IViewAbstraction view, IDataLayerAbstraction dataLayer)
{
this.dataLayer = dataLayer;
this.view = view;
this.view.ModelDataChangedCallback = OnModelChanged;
this.view.ModelData = dataLayer.GetData();
}
private void OnModelChanged(ModelData data)
{
// validate and save data.
}
}