主頁 > 知識庫 > 淺析MVP模式中V-P交互問題及案例分享

淺析MVP模式中V-P交互問題及案例分享

熱門標(biāo)簽:騰訊地圖標(biāo)注手機(jī) 百度地圖怎樣做地圖標(biāo)注 柳州電銷機(jī)器人公司 征途美甲店地圖標(biāo)注 電銷語音機(jī)器人型號參數(shù) 浦發(fā)電話機(jī)器人提醒還款 昆明語音電銷機(jī)器人價格 太原400電話上門辦理 400電話如何申請取消

在差不多兩年的時間內(nèi),我們項目組幾十來號人都撲在一個項目上面。這是一個基于微軟SCSF(Smart Client Software Factory)的項目,客戶端是墨爾本一家事業(yè)單位。前兩周,我奉命負(fù)責(zé)對某個模塊進(jìn)行Code Review工作,在此期間,發(fā)現(xiàn)了一些問題,也有了一些想法。不過,有些想法可能還不是很成熟,不能完全保證其正確性,有機(jī)會寫出來討論一下。今天來說說關(guān)于MVP的一些想法。

一、簡單講講MVP是什么玩意兒
如果從層次關(guān)系來講,MVP屬于Presentation層的設(shè)計模式。對于一個UI模塊來說,它的所有功能被分割為三個部分,分別通過Model、View和Presenter來承載。Model、View和Presenter相互協(xié)作,完成對最初數(shù)據(jù)的呈現(xiàn)和對用戶操作的響應(yīng),它們具有各自的職責(zé)劃分。Model可以看成是模塊的業(yè)務(wù)邏輯和數(shù)據(jù)的提供者;View專門負(fù)責(zé)數(shù)據(jù)可視化的呈現(xiàn),和用戶交互事件的相對應(yīng)。一般地,View會實現(xiàn)一個相應(yīng)的接口;Presenter是一般充當(dāng)Model和View的紐帶。

MVP具有很多的變體,其中最為常用的一種變體成為Passive View(被動視圖)。對于Passive View,Model、View和Presenter之間的關(guān)系如下圖所示。View和Modell之間不能直接交互,View通過Presenter與Model打交道。Presenter接受View的UI請求,完成簡單的UI處理邏輯,并調(diào)用Model進(jìn)行業(yè)務(wù)處理,并調(diào)用View將相應(yīng)的結(jié)果反映出來。View直接依賴Presenter,但是Presenter間接依賴View,它直接依賴的是View實現(xiàn)的接口。關(guān)于MVP和Passive View基本的常識性東西,不是本篇文章論述的重點,對此不清楚的讀者相信可以Google出很多相關(guān)的資料來,所以在這里就再多做介紹了。



二、Passive View模式的基本特征總結(jié)

Passive View,顧名思義,View是被動的。那么主動是誰呢?答案是Presenter。對于Presenter的主動性,我個人是這么理解的:

•Presenter是整個MVP體系的控制中心,而不是單純的處理View請求的人;
•View僅僅是用戶交互請求的匯報者,對于響應(yīng)用戶交互相關(guān)的邏輯和流程,View不參與決策,真正的決策者是Presenter;
•View向Presenter發(fā)送用戶交互請求應(yīng)該采用這樣的口吻:“我現(xiàn)在將用戶交互請求發(fā)送給你,你看著辦,需要我的時候我會協(xié)助你”,不應(yīng)該是這樣:“我現(xiàn)在處理用戶交互請求了,我知道該怎么辦,但是我需要你的支持,因為實現(xiàn)業(yè)務(wù)邏輯的Model只信任你”;
•對于綁定到View上的數(shù)據(jù),不應(yīng)該是View從Presenter上“拉”回來的,應(yīng)該是Presenter主動“推”給View的;
•View盡可能不維護(hù)數(shù)據(jù)狀態(tài),因為其本身僅僅實現(xiàn)單純的、獨立的UI操作;Presenter才是整個體系的協(xié)調(diào)者,它根據(jù)處理用于交互的邏輯給View和Model安排工作。

三、理想與現(xiàn)實的距離

上面對Passive View MVP特征的羅列,我覺得是一種理想狀態(tài)。是在大型項目中,尤其是項目的開發(fā)者自身并不完全理解MVP原理的情況下,要整體實現(xiàn)這樣的一種理想狀態(tài)是一件很難的事情。有人可能會說,在開發(fā)人員不了解MVP的情況下要求他們用好MVP,你這不是扯淡嗎?實際上,在這里并不是說開發(fā)人員完全沒有MVP關(guān)于關(guān)注點分離的概念,只是對MVP中的三元角色并沒有非常清晰的界定(實際上也沒有一個明確的規(guī)范對Model、View和Presenter具體的職責(zé)范圍進(jìn)行明確的劃分),在開發(fā)的時候,會不自覺地受傳統(tǒng)編程習(xí)慣的影響,將Presenter單純地當(dāng)成是View調(diào)用Model的中介。我經(jīng)常這么說:如果以View為中心,將Presenter當(dāng)成是View和Model的中間人,這也叫MVP模式,不過這里的P不是Presenter,而是Proxy,是Model在View的代理而已。

從Passive View中Model、View和Presenter三者之間的依賴關(guān)系來看,這個模型充分地給了開發(fā)者犯這樣錯誤的機(jī)會。注意上面的圖中View到Presenter的箭頭表明View是可以任意的調(diào)用Presenter的。開發(fā)人員完全有可能將大部分UI處理邏輯寫在View中,而Presenter僅僅對Model響應(yīng)操作的簡單調(diào)用。因為在我Review的各種所謂的MVP編程方式中,有不少是這么寫的。在很多情況下,甚至不用認(rèn)真去分析具體的代碼,從View和Presenter中代碼的行數(shù)就可以看出來,因為View的代碼和Presenter的代碼都不在一個數(shù)量級。

我現(xiàn)在的一個目的是提出一種編程模式,杜絕開發(fā)人員將程序?qū)懗苫赑roxy的MVP,在我看來,唯一的辦法就是盡量弱化(不可能剔除)View對Presenter的依賴。實際上,對于MVP來說,View僅僅向Presenter遞交用戶交互請求,僅此而已。如果我們將View對Presenter的這點依賴關(guān)系實現(xiàn)在框架層次中,最終開發(fā)人員的編程來說就不需要這種依賴了。那么我就可以通過一定的編程技巧使View根本無法訪問Presenter,從而避免Presenter成為Proxy的可能的。

那么,如果在不能獲得Presenter的情況下,使View能夠正常將請求遞交給Presenter呢?很簡單,通過事件訂閱機(jī)制就可以了,雖然View不可以獲取到Presenter,但是Presenter卻可以獲取到View,讓Presenter訂閱View的相關(guān)事件就可以的。

四、讓View不再依賴Presenter的編程模型

現(xiàn)在,我們就來如果通過一種簡單的編程模式就能夠讓View對Presenter的依賴完全地從中最終開發(fā)者的源代碼中移除。為此,我們需要定義一系列的基類,首先我為所有的View創(chuàng)建基類ViewBase,在這里我們直接用Form作為View,而在SCSF中View一般是通過UserControl來表示的。ViewBase定義如下,為了使View中不能調(diào)用Presenter,我將其定義成私有字段。那么,如何讓View和Presenter之間建立起關(guān)聯(lián)呢?在這里通過虛方法CreatePresenter,具體的View必須重寫該方法,不然會拋出一個NotImplementedException異常。在構(gòu)造函數(shù)中,調(diào)用該方法比用返回值為Presenter賦值。

復(fù)制代碼 代碼如下:

 using System;
 using System.ComponentModell;
 using System.Windows.Forms;
 namespace MVPDemo
 {
     public class ViewBase: Form
     {
         private object _presenter;

         public ViewBase()
         {
             _presenter = this.CreatePresenter();
         }

         protected virtual object CreatePresenter()
         {
             if (LicenseManager.CurrentContext.UsageModel == LicenseUsageModel.Designtime)
             {
                 return null;
             }
             else
             {
                 throw new NotImplementedException(string.Format("{0} must override the CreatePresenter method.", this.GetType().FullName));
             }
         }      
     }
 }

然后,我們也為所有的Presenter創(chuàng)建基類PresenterIView>,泛型類型IView表示具體View實現(xiàn)的接口。表示View的同名只讀屬性在構(gòu)造函數(shù)中賦值,賦值完成之后調(diào)用調(diào)用虛方法OnViewSet。具體的Presenter可以重寫該方法進(jìn)行對View進(jìn)行事件注冊工作。但是需要注意的是,Presenter的創(chuàng)建是在ViewBase的構(gòu)造函數(shù)中通過調(diào)用CreatePresenter方法實現(xiàn),所以執(zhí)行OnViewSet的時候,View本身還沒有完全初始化,所以在此不能對View的控件進(jìn)行操作。

復(fù)制代碼 代碼如下:

 namespace MVPDemo
 {
     public class PresenterIView>
     {
         public IView View { get; private set; }

         public Presenter(IView view)
         {
             this.View = view;
             this.OnViewSet();
         }
         protected virtual void OnViewSet()
         { }
     }
 }

由于,Presenter是通過接口的方式與View進(jìn)行交互的。在這里,由于View通過Form的形式體現(xiàn),有時候我們要通過這個接口訪問Form的一些屬性、方法和事件,需要將相應(yīng)的成員定義在接口上面,比較麻煩。此時,我們可以選擇將這些成員定義在一個接口中,具體View的接口繼承該接口就可以了。在這里,我們相當(dāng)是為所有的View接口創(chuàng)建了“基接口”。作為演示,我現(xiàn)在了Form的三個事件成員定義在街口IViewBase中。

復(fù)制代碼 代碼如下:

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

五、實例演示

上面我通過定義基類和接口為整個編程模型搭建了一個框架,現(xiàn)在我們通過一個具體的例子來介紹該編程模型的應(yīng)用。我們采用的是一個簡單的Windows Forms應(yīng)用,模擬管理客戶信息的場景,邏輯很簡單:程序啟動的時候顯示出所有的客戶端列表;用戶選擇某一客戶端,將響應(yīng)的信息顯示在TextBox中以供編輯;對客戶端信息進(jìn)行相應(yīng)修改之后,點擊OK按鈕進(jìn)行保存。整個操作界面如下圖所示:


首先,我們創(chuàng)建實體類Customer,簡單起見,僅僅包含四個屬性:Id、FirstName、LastName和Address:

復(fù)制代碼 代碼如下:

 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三種角色,特意創(chuàng)建一個CustomerModel類型,實際上在真實的應(yīng)用中,并沒有單獨一個類型來表示Model。CustomerModel維護(hù)客戶列表,體統(tǒng)相關(guān)的查詢和更新操作。CustomerModel定義如下:

復(fù)制代碼 代碼如下:

 using System.Collections.Generic;
 using System.Linq;
 namespace MVPDemo
 {
     public class CustomerModel
     {
         private IListCustomer> _customers = new ListCustomer>{
             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.ToArrayCustomer>()[0];
         }

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

接著,我們定義View的接口ICustomerView。ICustomerView定義了兩個事件,CustomerSelected在用戶從Gird中選擇了某個條客戶記錄是觸發(fā),而CustomerSaving則在用戶完成編輯點擊OK按鈕視圖提交修改時觸發(fā)。ICustomerView還定義了View必須完成的三個基本操作:綁定客戶列表(ListAllCustomers);顯示單個客戶信息到TextBox(DisplayCustomerInfo);保存后清空可編輯控件(Clear)。

復(fù)制代碼 代碼如下:

 using System;
 namespace MVPDemo
 {
     public interface ICustomerView : IViewBase
     {
         event EventHandlerCustomerEventArgs> CustomerSelected;

         event EventHandlerCustomerEventArgs> CustomerSaving;

         void ListAllCustomers(Customer[] customers);

         void DisplayCustomerInfo(Customer customer);

         void Clear();
     }
 }

事件參數(shù)的類型CustomerEventArgs定義如下,兩個屬性CustomerId和Customer分別代表客戶ID和具體的客戶,它們分別用于上面提到的CustomerSelected和CustomerSaving事件。

復(fù)制代碼 代碼如下:

 using System;
 namespace MVPDemo
 {
     public class CustomerEventArgs : EventArgs
     {
         public string CustomerId
         { get; set; }

         public Customer Customer
         { get; set; }
     }
 }

而具體的Presenter定義在如下的CustomerPresenter類型中。在重寫的OnViewSet方法中注冊View的三個事件:Load事件中調(diào)用Model獲取所有客戶列表,并顯示在View的Grid上;CustomerSelected事件中通過事件參數(shù)傳遞的客戶ID調(diào)用Model獲取相應(yīng)的客戶信息,顯示在View的可編輯控件上;CustomerSaving則通過事件參數(shù)傳遞的被更新過的客戶信息,調(diào)用Model提交更新。

復(fù)制代碼 代碼如下:

 using System.Windows.Forms;

 namespace MVPDemo
 {  
     public class CustomerPresenter: PresenterICustomerView>
     {
         public CustomerModel Model
         { get; private set; }

         public CustomerPresenter(ICustomerView view)
             : base(view)
         {
             this.Model = new CustomerModel();
         }

         protected override void OnViewSet()
         {
             this.View.Load += (sender, args) =>
                 {
                     Customer[] customers = this.Model.GetAllCustomers();
                     this.View.ListAllCustomers(customers);
                     this.View.Clear();
                 };
             this.View.CustomerSelected += (sender, args) =>
                 {
                     Customer customer = this.Model.GetCustomerById(args.CustomerId);
                     this.View.DisplayCustomerInfo(customer);
                 };
             this.View.CustomerSaving += (sender, args) =>
                 {
                     this.Model.UpdateCustomer(args.Customer);
                     Customer[] customers = this.Model.GetAllCustomers();
                     this.View.ListAllCustomers(customers);
                     this.View.Clear();
                     MessageBox.Show("The customer has been successfully updated!", "Successfully Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 };
         }      
     }
 }

對于具體的View來說,僅僅需要實現(xiàn)ICustomerView,并處理響應(yīng)控件事件即可(主要是用戶從Grid中選擇某個記錄觸發(fā)的RowHeaderMouseClick事件,以及點擊OK的事件)。實際上不需要View親自處理這些事件,而僅僅需要觸發(fā)相應(yīng)的事件,讓事件訂閱者(Presenter)來處理就可以了。此外還需要重寫CreatePresenter方法完成對CustomerPresenter的創(chuàng)建。CustomerView定義如下:

復(fù)制代碼 代碼如下:

 using System;
 using System.Windows.Forms;

 namespace MVPDemo
 {
     public partial class CustomerView : ViewBase, ICustomerView
     {
         public CustomerView()
         {
             InitializeComponent();           
         }

         protected override object CreatePresenter()
         {
             return new CustomerPresenter(this);
         }

         #region ICustomerView Members

         public event EventHandlerCustomerEventArgs> CustomerSelected;

         public event EventHandlerCustomerEventArgs> CustomerSaving;

         public void ListAllCustomers(Customer[] customers)
         {
             this.dataGridViewCustomers.DataSource = customers;
         }

         public void DisplayCustomerInfo(Customer customer)
         {
             this.buttonOK.Enabled = true;
             this.textBoxId.Text = customer.Id;
             this.textBox1stName.Text = customer.FirstName;
             this.textBoxLastName.Text = customer.LastName;
             this.textBoxAddress.Text = customer.Address;
         }

         public void Clear()
         {
             this.buttonOK.Enabled       = false;
             this.textBox1stName.Text    = string.Empty;
             this.textBoxLastName.Text   = string.Empty;
             this.textBoxAddress.Text    = string.Empty;
             this.textBoxId.Text         = string.Empty;
         }

         #endregion

         protected virtual void OnCustomerSelected(string customerId)
         {
             var previousId = this.textBoxId.Text.Trim();
             if (customerId == previousId)
             {
                 return;
             }
             if(null != this.CustomerSelected)
             {
                 this.CustomerSelected(this, new CustomerEventArgs{ CustomerId = customerId});
             }
         }

         protected virtual void OnCustomerSaving(Customer customer)
         {
             if(null != this.CustomerSaving)
             {
                 this.CustomerSaving(this, new CustomerEventArgs{ Customer = customer});
             }
         }

         private void dataGridViewCustomers_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
         {  
             var currentRow = this.dataGridViewCustomers.Rows[e.RowIndex];
             var customerId = currentRow.Cells[0].Value.ToString();
             this.OnCustomerSelected(customerId);
         }

         private void buttonOK_Click(object sender, EventArgs e)
         {
             var customer        = new Customer();
             customer.Id         = this.textBoxId.Text.Trim();
             customer.FirstName  = this.textBox1stName.Text.Trim();
             customer.LastName   = this.textBoxLastName.Text.Trim();
             customer.Address    = this.textBoxAddress.Text.Trim();
             this.OnCustomerSaving(customer);
         }
     }
 }

您可能感興趣的文章:
  • Android開發(fā)之文件操作模式深入理解
  • android開發(fā)中使用java觀察者模式
  • ASP.NET小結(jié)之MVC, MVP, MVVM比較以及區(qū)別(一)
  • ASP.NET小結(jié)之MVC, MVP, MVVM比較以及區(qū)別(二)
  • Android開發(fā)中的MVC設(shè)計模式淺析
  • 詳解Android MVP開發(fā)模式

標(biāo)簽:德陽 張家界 天門 江蘇 蘭州 陽泉 新疆 白山

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《淺析MVP模式中V-P交互問題及案例分享》,本文關(guān)鍵詞  淺析,MVP,模式,中,V-P,交互,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《淺析MVP模式中V-P交互問題及案例分享》相關(guān)的同類信息!
  • 本頁收集關(guān)于淺析MVP模式中V-P交互問題及案例分享的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章