在MVP模式中,我可以在不同的项目中创建View和Presenter吗?

4
我正在学习MVP模式,以应对当前项目(Windows应用程序)的开发。我在使用Silverlight和WPF时已经有了很好的MVVM工作经验。
在MVVM中,我的View和ViewModel通常会分别放在不同的项目中,它们通过WPF的强大绑定相互通信。
但是,在MVP中,我在互联网上看到的大多数示例中,View和Presenter都在同一个项目中。
因此,我的问题是: 是否有办法将View和Presenter创建在不同的项目中?我的意思是将View作为Windows应用程序,而将Presenter作为类库项目。
如果可以,那么如何让我的View和Presenter相互引用?
1个回答

2

您的主持人应该只通过接口与视图进行通信。

您的主持人和视图接口可以包含在类库项目中,Windows 应用程序可以引用该项目。 在 Windows 应用程序项目中创建的任何具体视图都可以实现适当的视图接口。

下面的简单示例显示了这些类如何相互交互。

ClassLibrary.dll

public class Presenter {

    // Repository class used to retrieve data
    private IRepository<Item> repository = ...;

    public void View { get; set; }

    public void LoadData() {
        // Retrieve your data from a repository or service
        IEnumerable<Item> items = repository.find(...);
        this.View.DisplayItems(items);
    }
}

public interface IView {
    void DisplayItems(IEnumerable<Item> items);
}

WindowsApplication.dll

public class ConcreteView : IView {

    private Button btn
    private Grid grid;
    private Presenter presenter = new Presenter();        

    public ConcreteView() {
        presenter.View = this;
        btn.Click += (s, a) => presenter.LoadData();
    }

    public void DisplayItems(IEnumerable<Item> items) {
        // enumerate the items and add them to your grid...
    }
}

#Benjamin Gale 感谢您的解释,但是我对这种模式非常陌生。您能否提供一个示例,例如如何使用MVP模式在单击加载按钮时将数据加载到网格中。 - Nijith Pavithran
#Benjamin Gale 谢谢,这对我很有帮助。 - Nijith Pavithran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接