开发者

How not to create presenter object in view?

I'm currently trying out some MVP patterns sample and I have been told not create concrete Presenter objec开发者_如何转开发ts in the View. Is there any way to have Presenter objects created dynamically ?

public partial class View: Window, IView
{
   private Presenter _presenter;

    public View()
    {
        InitializeComponent();
        _presenter = new Presenter(this); //Asked to avoid this
    }
}


You're thinking it wrong. You don't create the presenter in the view. You create it elsewhere (application startup, other presenters) and it passes itself to the view, either as a constructor parameter, or by setting a property.

Like this:

class FooView : IFooView
{
    private readonly IFooPresenter presenter;

    public FooView(IFooPresenter presenter)
    {
        this.presenter = presenter;
    }
}

class FooPresenter1 : IFooPresenter
{
    private readonly IFooView view;

    public FooPresenter1()
    {
        view = new FooView(this);
    }
}
// or
class FooPresenter2 : IFooPresenter
{
    private readonly IFooView view;

    public FooPresenter2(IFooView view)
    {
        this.view = view;
        view.Presenter = this;
    }
}

And by the way, you seem to be using WPF. If that's the case you may want to have a look at the Model-View-ViewModel pattern instead.


With view first creation you can use an IoC container to create your Presenter:

public View(IMyPresenter presenter)
{
    InitializeComponent();
    _presenter = presenter;
}

Alternatively, you can use model (presenter) first where the View is passed to the Presenter in much the same way. See Which came first, the View or the Model? for discussion on this topic.

Or you could use a third object to bind the View and Presenter together, like the IBinder service in Caliburn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜