P交互问题及案例分享(3)


 using System;
 using System.ComponentModell;
 namespace MVPDemo
 {
    public interface IViewBase
     {
        event EventHandler Load;
        event EventHandler Closed;
        event CancelEventHandler Closing;
     }
 }

五、实例演示

上面我通过定义基类和接口为整个编程模型搭建了一个框架,现在我们通过一个具体的例子来介绍该编程模型的应用。我们采用的是一个简单的Windows Forms应用,模拟管理客户信息的场景,逻辑很简单:程序启动的时候显示出所有的客户端列表;用户选择某一客户端,将响应的信息显示在TextBox中以供编辑;对客户端信息进行相应修改之后,点击OK按钮进行保存。整个操作界面如下图所示:


P交互问题及案例分享

首先,我们创建实体类Customer,简单起见,仅仅包含四个属性:Id、FirstName、LastName和Address:

复制代码 代码如下:


 using System;
 namespace MVPDemo
 {
     public class Customer: ICloneable
     {
         public string Id
         { get; set; }

         public string FirstName
         { get; set; }

         public string LastName
         { get; set; }

         public string Address
         { get; set; }      

         object ICloneable.Clone()
         {
             return this.Clone();
         }

         public Customer Clone()
         {
             return new Customer {
                 Id          = this.Id,
                 FirstName   = this.FirstName,
                 LastName    = this.LastName,
                 Address     = this.Address
             };
         }
     }
 }

然后,为了真实模拟MVP三种角色,特意创建一个CustomerModel类型,实际上在真实的应用中,并没有单独一个类型来表示Model。CustomerModel维护客户列表,体统相关的查询和更新操作。CustomerModel定义如下:

复制代码 代码如下:


 using System.Collections.Generic;
 using System.Linq;
 namespace MVPDemo
 {
     public class CustomerModel
     {
         private IList<Customer> _customers = new List<Customer>{
             new Customer{ Id = "001", FirstName = "San", LastName = "Zhang", Address="Su zhou"},
             new Customer{ Id = "002", FirstName = "Si", LastName = "Li", Address="Shang Hai"}
         };

         public void UpdateCustomer(Customer customer)
         {
             for (int i = 0; i < _customers.Count; i++)
             {
                 if (_customers[i].Id == customer.Id)
                 {
                     _customers[i] = customer;
                     break;
                 }
             }
         }

         public Customer GetCustomerById(string id)
         {
             var customers = from customer in _customers
                             where customer.Id == id
                             select customer.Clone();
             return customers.ToArray<Customer>()[0];
         }

         public Customer[] GetAllCustomers()
         {
             var customers = from customer in _customers
                             select customer.Clone();
             return customers.ToArray<Customer>();
         }
     }
 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzfzs.html