谈谈关于MVP模式中V-P交互问题
在差不多兩年的時間內(nèi),我們項目組幾十來號人都撲在一個項目上面。這是一個基于微軟SCSF(Smart Client Software Factory)的項目,客戶端是墨爾本一家事業(yè)單位。前兩周,我奉命負(fù)責(zé)對某個模塊進(jìn)行Code Review工作,在此期間,發(fā)現(xiàn)了一些問題,也有了一些想法。不過,有些想法可能還不是很成熟,不能完全保證其正確性,有機會寫出來討論一下。今天來說說關(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ā)者犯這樣錯誤的機會。注意上面的圖中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呢?很簡單,通過事件訂閱機制就可以了,雖然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賦值。
1: using System; 2: using System.ComponentModell; 3: using System.Windows.Forms; 4: namespace MVPDemo 5: { 6: public class ViewBase: Form 7: { 8: private object _presenter; 9:? 10: public ViewBase() 11: { 12: _presenter = this.CreatePresenter(); 13: } 14:? 15: protected virtual object CreatePresenter() 16: { 17: if (LicenseManager.CurrentContext.UsageModel == LicenseUsageModel.Designtime) 18: { 19: return null; 20: } 21: else 22: { 23: throw new NotImplementedException(string.Format("{0} must override the CreatePresenter method.", this.GetType().FullName)); 24: } 25: } 26: } 27: }?
然后,我們也為所有的Presenter創(chuàng)建基類Presenter<IView>,泛型類型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)行操作。
1: namespace MVPDemo 2: { 3: public class Presenter<IView> 4: { 5: public IView View { get; private set; } 6:? 7: public Presenter(IView view) 8: { 9: this.View = view; 10: this.OnViewSet(); 11: } 12: protected virtual void OnViewSet() 13: { } 14: } 15: }由于,Presenter是通過接口的方式與View進(jìn)行交互的。在這里,由于View通過Form的形式體現(xiàn),有時候我們要通過這個接口訪問Form的一些屬性、方法和事件,需要將相應(yīng)的成員定義在接口上面,比較麻煩。此時,我們可以選擇將這些成員定義在一個接口中,具體View的接口繼承該接口就可以了。在這里,我們相當(dāng)是為所有的View接口創(chuàng)建了“基接口”。作為演示,我現(xiàn)在了Form的三個事件成員定義在街口IViewBase中。
1: using System; 2: using System.ComponentModell; 3: namespace MVPDemo 4: { 5: public interface IViewBase 6: { 7: event EventHandler Load; 8: event EventHandler Closed; 9: event CancelEventHandler Closing; 10: } 11: }五、實例演示
上面我通過定義基類和接口為整個編程模型搭建了一個框架,現(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:
1: using System; 2: namespace MVPDemo 3: { 4: public class Customer: ICloneable 5: { 6: public string Id 7: { get; set; } 8:? 9: public string FirstName 10: { get; set; } 11:? 12: public string LastName 13: { get; set; } 14:? 15: public string Address 16: { get; set; } 17:? 18: object ICloneable.Clone() 19: { 20: return this.Clone(); 21: } 22:? 23: public Customer Clone() 24: { 25: return new Customer { 26: Id = this.Id, 27: FirstName = this.FirstName, 28: LastName = this.LastName, 29: Address = this.Address 30: }; 31: } 32: } 33: }?
然后,為了真實模擬MVP三種角色,特意創(chuàng)建一個CustomerModel類型,實際上在真實的應(yīng)用中,并沒有單獨一個類型來表示Model。CustomerModel維護(hù)客戶列表,體統(tǒng)相關(guān)的查詢和更新操作。CustomerModel定義如下:
1: using System.Collections.Generic; 2: using System.Linq; 3: namespace MVPDemo 4: { 5: public class CustomerModel 6: { 7: private IList<Customer> _customers = new List<Customer>{ 8: new Customer{ Id = "001", FirstName = "San", LastName = "Zhang", Address="Su zhou"}, 9: new Customer{ Id = "002", FirstName = "Si", LastName = "Li", Address="Shang Hai"} 10: }; 11:? 12: public void UpdateCustomer(Customer customer) 13: { 14: for (int i = 0; i < _customers.Count; i++) 15: { 16: if (_customers[i].Id == customer.Id) 17: { 18: _customers[i] = customer; 19: break; 20: } 21: } 22: } 23:? 24: public Customer GetCustomerById(string id) 25: { 26: var customers = from customer in _customers 27: where customer.Id == id 28: select customer.Clone(); 29: return customers.ToArray<Customer>()[0]; 30: } 31:? 32: public Customer[] GetAllCustomers() 33: { 34: var customers = from customer in _customers 35: select customer.Clone(); 36: return customers.ToArray<Customer>(); 37: } 38: } 39: }接著,我們定義View的接口ICustomerView。ICustomerView定義了兩個事件,CustomerSelected在用戶從Gird中選擇了某個條客戶記錄是觸發(fā),而CustomerSaving則在用戶完成編輯點擊OK按鈕視圖提交修改時觸發(fā)。ICustomerView還定義了View必須完成的三個基本操作:綁定客戶列表(ListAllCustomers);顯示單個客戶信息到TextBox(DisplayCustomerInfo);保存后清空可編輯控件(Clear)。
1: using System; 2: namespace MVPDemo 3: { 4: public interface ICustomerView : IViewBase 5: { 6: event EventHandler<CustomerEventArgs> CustomerSelected; 7:? 8: event EventHandler<CustomerEventArgs> CustomerSaving; 9:? 10: void ListAllCustomers(Customer[] customers); 11:? 12: void DisplayCustomerInfo(Customer customer); 13:? 14: void Clear(); 15: } 16: }?
事件參數(shù)的類型CustomerEventArgs定義如下,兩個屬性CustomerId和Customer分別代表客戶ID和具體的客戶,它們分別用于上面提到的CustomerSelected和CustomerSaving事件。
1: using System; 2: namespace MVPDemo 3: { 4: public class CustomerEventArgs : EventArgs 5: { 6: public string CustomerId 7: { get; set; } 8:? 9: public Customer Customer 10: { get; set; } 11: } 12: }而具體的Presenter定義在如下的CustomerPresenter類型中。在重寫的OnViewSet方法中注冊View的三個事件:Load事件中調(diào)用Model獲取所有客戶列表,并顯示在View的Grid上;CustomerSelected事件中通過事件參數(shù)傳遞的客戶ID調(diào)用Model獲取相應(yīng)的客戶信息,顯示在View的可編輯控件上;CustomerSaving則通過事件參數(shù)傳遞的被更新過的客戶信息,調(diào)用Model提交更新。
1: using System.Windows.Forms; 2:? 3: namespace MVPDemo 4: { 5: public class CustomerPresenter: Presenter<ICustomerView> 6: { 7: public CustomerModel Model 8: { get; private set; } 9: 10: public CustomerPresenter(ICustomerView view) 11: : base(view) 12: { 13: this.Model = new CustomerModel(); 14: } 15:? 16: protected override void OnViewSet() 17: { 18: this.View.Load += (sender, args) => 19: { 20: Customer[] customers = this.Model.GetAllCustomers(); 21: this.View.ListAllCustomers(customers); 22: this.View.Clear(); 23: }; 24: this.View.CustomerSelected += (sender, args) => 25: { 26: Customer customer = this.Model.GetCustomerById(args.CustomerId); 27: this.View.DisplayCustomerInfo(customer); 28: }; 29: this.View.CustomerSaving += (sender, args) => 30: { 31: this.Model.UpdateCustomer(args.Customer); 32: Customer[] customers = this.Model.GetAllCustomers(); 33: this.View.ListAllCustomers(customers); 34: this.View.Clear(); 35: MessageBox.Show("The customer has been successfully updated!", "Successfully Update", MessageBoxButtons.OK, MessageBoxIcon.Information); 36: }; 37: } 38: } 39: }對于具體的View來說,僅僅需要實現(xiàn)ICustomerView,并處理響應(yīng)控件事件即可(主要是用戶從Grid中選擇某個記錄觸發(fā)的RowHeaderMouseClick事件,以及點擊OK的事件)。實際上不需要View親自處理這些事件,而僅僅需要觸發(fā)相應(yīng)的事件,讓事件訂閱者(Presenter)來處理就可以了。此外還需要重寫CreatePresenter方法完成對CustomerPresenter的創(chuàng)建。CustomerView定義如下:
1: using System; 2: using System.Windows.Forms; 3:? 4: namespace MVPDemo 5: { 6: public partial class CustomerView : ViewBase, ICustomerView 7: { 8: public CustomerView() 9: { 10: InitializeComponent(); 11: } 12:? 13: protected override object CreatePresenter() 14: { 15: return new CustomerPresenter(this); 16: } 17:? 18: #region ICustomerView Members 19:? 20: public event EventHandler<CustomerEventArgs> CustomerSelected; 21:? 22: public event EventHandler<CustomerEventArgs> CustomerSaving; 23:? 24: public void ListAllCustomers(Customer[] customers) 25: { 26: this.dataGridViewCustomers.DataSource = customers; 27: } 28:? 29: public void DisplayCustomerInfo(Customer customer) 30: { 31: this.buttonOK.Enabled = true; 32: this.textBoxId.Text = customer.Id; 33: this.textBox1stName.Text = customer.FirstName; 34: this.textBoxLastName.Text = customer.LastName; 35: this.textBoxAddress.Text = customer.Address; 36: } 37:? 38: public void Clear() 39: { 40: this.buttonOK.Enabled = false; 41: this.textBox1stName.Text = string.Empty; 42: this.textBoxLastName.Text = string.Empty; 43: this.textBoxAddress.Text = string.Empty; 44: this.textBoxId.Text = string.Empty; 45: } 46:? 47: #endregion 48:? 49: protected virtual void OnCustomerSelected(string customerId) 50: { 51: var previousId = this.textBoxId.Text.Trim(); 52: if (customerId == previousId) 53: { 54: return; 55: } 56: if(null != this.CustomerSelected) 57: { 58: this.CustomerSelected(this, new CustomerEventArgs{ CustomerId = customerId}); 59: } 60: } 61:? 62: protected virtual void OnCustomerSaving(Customer customer) 63: { 64: if(null != this.CustomerSaving) 65: { 66: this.CustomerSaving(this, new CustomerEventArgs{ Customer = customer}); 67: } 68: } 69:? 70: private void dataGridViewCustomers_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) 71: { 72: var currentRow = this.dataGridViewCustomers.Rows[e.RowIndex]; 73: var customerId = currentRow.Cells[0].Value.ToString(); 74: this.OnCustomerSelected(customerId); 75: } 76:? 77: private void buttonOK_Click(object sender, EventArgs e) 78: { 79: var customer = new Customer(); 80: customer.Id = this.textBoxId.Text.Trim(); 81: customer.FirstName = this.textBox1stName.Text.Trim(); 82: customer.LastName = this.textBoxLastName.Text.Trim(); 83: customer.Address = this.textBoxAddress.Text.Trim(); 84: this.OnCustomerSaving(customer); 85: } 86: } 87: }總結(jié)
以上是生活随笔為你收集整理的谈谈关于MVP模式中V-P交互问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 动态内存(Dynamic Memory)
- 下一篇: JavaWeb中的Session、Ses