[英]A general question on model-view-presenter (C#), should the model know the presenter?
[英]Model View Presenter Interface question?
我需要您的帮助才能了解MVP。 我使用了一个界面( IProductEditorView
)。 如果您在下面看,则可以看到表示层:
using System;
using System.Collections.Generic;
using System.Text;
using MVPProject.BusinessLayer;
namespace MVPProject.PresentationLayer
{
public interface IProductEditorView
{
int ProductID { get;}
string ProductDescription { get; }
event EventHandler<EventArgs> Save;
}
public class ProductEditorPresenter
{
private IProductEditorView mView;
public ProductEditorPresenter(IProductEditorView view)
{
this.mView = view;
this.Initialize();
}
private void Initialize()
{
this.mView.Save += new EventHandler<EventArgs>(mView_Save);
}
private void mView_Save(object sender, EventArgs e)
{
Product product;
try
{
product = new Product();
product.Description = mView.ProductDescription;
product.ID = mView.ProductID;
product.Save();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
throw;
}
}
}
}
如果您在下面看,您会看到; 这让我很ProductListPresenter(IProductEditorView view)
因为ProductListPresenter(IProductEditorView view)
但他们要我添加(this)
。 我不明白为什么 “ this.mPresenter = new ProductListPresenter(this);
”?
private ProductListPresenter mPresenter;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.mPresenter = new ProductListPresenter(this);
}
我做MVP的方法是让演示者拥有一个名为Initialize的方法,该方法将视图作为参数。 想到MVP的一种方法是演示者正在通过视图界面操纵视图。 让我们举个例子,当单击“保存”按钮的OnClick事件时,您希望主持人保存产品并且该代码不直接放在页面后面的代码中。 您可以编写如下代码:
public class ProductEditorPresenter
{
public void Initialize(IProductEditorView view, IProductBuilder productBuilder)
{
view.SaveProduct += delegate
{
var product = productBuilder.Create(view.ProductId, view.ProductDescription);
product.Save();
}
}
}
productBuilder在其中为您处理产品的创建。 您确实确实想尝试进行基于接口/合同的编程,而不是直接在类中创建具体对象。 另外,杰里米·米勒(Jeremy Miller)还创建了一个有关演示模式的Wiki,这可能对甚至更详细地描述这种模式很有用。 可以在这里看到
假定第二个代码块是asp.net表单代码的一部分,那么我可以想象asp.net表单实现了IProductEditorView接口,因此您将视图(this)传递给了主持人。
假设代码的第二部分是从视图来看的,则您的MVP模式实现存在问题。
在您的设计中,演示者和视图都彼此了解(Presenter在其构造函数中接受视图,并且视图在OnInit上设置其演示者)。
这是一个问题,因为您使用MVP解耦视图和演示者,但是这种设计使它们紧密耦合。 演示者不需要了解您的视图,因此可以从演示者构造函数中删除IProductEditorView参数。
然后,您需要将保存方法更改为此:
private void Save(Product product)
{
try
{
product.Save();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
throw;
}
}
在您看来,当您需要保存产品时,请进行准备并将其传递给演示者:
private btnSaveProduct_Click(object sender, EventArgs e)
{
Product product;
product.Description = txtDescription.Text;
// Set other properties or the product
this.mPresenter.Save(product);
}
您的视图的OnInit保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.