MVP是一种广泛使用的UI架构模式,适用于基于事件驱动的应用框架。
能够与 Model直接进行交互的仅限于 Presenter, View 只能通过 Presenter 间拉地调用 Model。
MVP分PV(Passive View) 和 (Supervising Controller)两种模式
SC(Supervising Controller)
public partial class WebForm1 : System.Web.UI.Page,IEmployeeSearchView
{
public EmployeeSearchPresenter Presenter { get; private set; }
public event EventHandler<DepartmentSelectedEventArgs> DepartmentSelected;
public WebForm1()
{
this.Presenter = new EmployeeSearchPresenter(this);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.Presenter.Initialize();
}
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
string department = this.DropDownListDepartments.SelectedValue;
DepartmentSelectedEventArgs eventArgs = new DepartmentSelectedEventArgs(department);
if (null != DepartmentSelected)
{
DepartmentSelected(this, eventArgs);
}
}
public void BindEmployees(IEnumerable<Employee> employees)
{
this.GridViewEmployees.DataSource = employees;
this.GridViewEmployees.DataBind();
}
public void BindDepartments(IEnumerable<string> departments)
{
this.DropDownListDepartments.DataSource = departments;
this.DropDownListDepartments.DataBind();
}
}
public class EmployeeSearchPresenter
{
public IEmployeeSearchView View { get; private set; }
public EmployeeRepository Repository { get; private set; }
public EmployeeSearchPresenter(IEmployeeSearchView view)
{
this.View = view;
this.Repository = new EmployeeRepository();
this.View.DepartmentSelected += OnDepartmentSelected;
}
private void OnDepartmentSelected(object sender, DepartmentSelectedEventArgs e)
{
string department = e.Department;
var employees = this.Repository.GetEmployees(department);
this.View.BindEmployees(employees);
}
public void Initialize()
{
IEnumerable<Employee> employees = this.Repository.GetEmployees();
this.View.BindEmployees(employees);
string[] departments = new string[] { "销售部", "采购部", "人事部", "IT部" };
this.View.BindDepartments(departments);
}
}
public class DepartmentSelectedEventArgs : EventArgs
{
public string Department { get; private set; }
public DepartmentSelectedEventArgs(string department)
{
this.Department = department;
}
}
public interface IEmployeeSearchView
{
void BindEmployees(IEnumerable<Employee> employees);
void BindDepartments(IEnumerable<string> departments);
event EventHandler<DepartmentSelectedEventArgs> DepartmentSelected;
}
public class EmployeeRepository
{
private static IList<Employee> employees;
static EmployeeRepository()
{
employees = new List<Employee>();
employees.Add(new Employee("001", "张三", "男", new DateTime(1981, 8, 24), "销售部"));
employees.Add(new Employee("002", "李四", "女", new DateTime(1982, 7, 24), "人事部"));
employees.Add(new Employee("003", "王五", "男", new DateTime(1981, 9, 21), "销售部"));
employees.Add(new Employee("004", "张三1", "男", new DateTime(1981, 8, 24), "销售部"));
employees.Add(new Employee("005", "张三2", "男", new DateTime(1981, 8, 24), "销售部"));
employees.Add(new Employee("006", "张三3