[转]谈谈关于MVP模式中V-P交互问题
在差不多两年的时间内,我们项目组几十来号人都扑在一个项目上面。这是一个基于微软SCSF(Smart Client Software Factory)的项目,客户端是墨尔本一家事业单位。前两周,我奉命负责对某个模块进行Code Review工作,在此期间,发现了一些问题,也有了一些想法。不过,有些想法可能还不是很成熟,不能完全保证其正确性,有机会写出来讨论一下。今天来说说关于MVP的一些想法。
一、简单讲讲MVP是什么玩意儿
如果从层次关系来讲,MVP属于Presentation层的设计模式。对于一个UI模块来说,它的所有功能被分割为三个部分,分别通过Model、View和Presenter来承载。Model、View和Presenter相互协作,完成对最初数据的呈现和对用户操作的响应,它们具有各自的职责划分。Model可以看成是模块的业务逻辑和数据的提供者;View专门负责数据可视化的呈现,和用户交互事件的相对应。一般地,View会实现一个相应的接口;Presenter是一般充当Model和View的纽带。
MVP具有很多的变体,其中最为常用的一种变体成为Passive View(被动视图)。对于Passive View,Model、View和Presenter之间的关系如下图所示。View和Modell之间不能直接交互,View通过Presenter与Model打交道。Presenter接受View的UI请求,完成简单的UI处理逻辑,并调用Model进行业务处理,并调用View将相应的结果反映出来。View直接依赖Presenter,但是Presenter间接依赖View,它直接依赖的是View实现的接口。关于MVP和Passive View基本的常识性东西,不是本篇文章论述的重点,对此不清楚的读者相信可以Google出很多相关的资料来,所以在这里就再多做介绍了。
二、Passive View模式的基本特征总结
Passive View,顾名思义,View是被动的。那么主动是谁呢?答案是Presenter。对于Presenter的主动性,我个人是这么理解的:
- Presenter是整个MVP体系的控制中心,而不是单纯的处理View请求的人;
- View仅仅是用户交互请求的汇报者,对于响应用户交互相关的逻辑和流程,View不参与决策,真正的决策者是Presenter;
- View向Presenter发送用户交互请求应该采用这样的口吻:“我现在将用户交互请求发送给你,你看着办,需要我的时候我会协助你”,不应该是这样:“我现在处理用户交互请求了,我知道该怎么办,但是我需要你的支持,因为实现业务逻辑的Model只信任你”;
- 对于绑定到View上的数据,不应该是View从Presenter上“拉”回来的,应该是Presenter主动“推”给View的;
- View尽可能不维护数据状态,因为其本身仅仅实现单纯的、独立的UI操作;Presenter才是整个体系的协调者,它根据处理用于交互的逻辑给View和Model安排工作。
三、理想与现实的距离
上面对Passive View MVP特征的罗列,我觉得是一种理想状态。是在大型项目中,尤其是项目的开发者自身并不完全理解MVP原理的情况下,要整体实现这样的一种理想状态是一件很难的事情。有人可能会说,在开发人员不了解MVP的情况下要求他们用好MVP,你这不是扯淡吗?实际上,在这里并不是说开发人员完全没有MVP关于关注点分离的概念,只是对MVP中的三元角色并没有非常清晰的界定(实际上也没有一个明确的规范对Model、View和Presenter具体的职责范围进行明确的划分),在开发的时候,会不自觉地受传统编程习惯的影响,将Presenter单纯地当成是View调用Model的中介。我经常这么说:如果以View为中心,将Presenter当成是View和Model的中间人,这也叫MVP模式,不过这里的P不是Presenter,而是Proxy,是Model在View的代理而已。
从Passive View中Model、View和Presenter三者之间的依赖关系来看,这个模型充分地给了开发者犯这样错误的机会。注意上面的图中View到Presenter的箭头表明View是可以任意的调用Presenter的。开发人员完全有可能将大部分UI处理逻辑写在View中,而Presenter仅仅对Model响应操作的简单调用。因为在我Review的各种所谓的MVP编程方式中,有不少是这么写的。在很多情况下,甚至不用认真去分析具体的代码,从View和Presenter中代码的行数就可以看出来,因为View的代码和Presenter的代码都不在一个数量级。
我现在的一个目的是提出一种编程模式,杜绝开发人员将程序写成基于Proxy的MVP,在我看来,唯一的办法就是尽量弱化(不可能剔除)View对Presenter的依赖。实际上,对于MVP来说,View仅仅向Presenter递交用户交互请求,仅此而已。如果我们将View对Presenter的这点依赖关系实现在框架层次中,最终开发人员的编程来说就不需要这种依赖了。那么我就可以通过一定的编程技巧使View根本无法访问Presenter,从而避免Presenter成为Proxy的可能的。
那么,如果在不能获得Presenter的情况下,使View能够正常将请求递交给Presenter呢?很简单,通过事件订阅机制就可以了,虽然View不可以获取到Presenter,但是Presenter却可以获取到View,让Presenter订阅View的相关事件就可以的。
四、让View不再依赖Presenter的编程模型
现在,我们就来如果通过一种简单的编程模式就能够让View对Presenter的依赖完全地从中最终开发者的源代码中移除。为此,我们需要定义一系列的基类,首先我为所有的View创建基类ViewBase,在这里我们直接用Form作为View,而在SCSF中View一般是通过UserControl来表示的。ViewBase定义如下,为了使View中不能调用Presenter,我将其定义成私有字段。那么,如何让View和Presenter之间建立起关联呢?在这里通过虚方法CreatePresenter,具体的View必须重写该方法,不然会抛出一个NotImplementedException异常。在构造函数中,调用该方法比用返回值为Presenter赋值。
: 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创建基类Presenter<IView>,泛型类型IView表示具体View实现的接口。表示View的同名只读属性在构造函数中赋值,赋值完成之后调用调用虚方法OnViewSet。具体的Presenter可以重写该方法进行对View进行事件注册工作。但是需要注意的是,Presenter的创建是在ViewBase的构造函数中通过调用CreatePresenter方法实现,所以执行OnViewSet的时候,View本身还没有完全初始化,所以在此不能对View的控件进行操作。
: namespace MVPDemo
: {
: public class Presenter<IView>
: {
: public IView View { get; private set; }
:
: public Presenter(IView view)
: {
: this.View = view;
: this.OnViewSet();
: }
: protected virtual void OnViewSet()
: { }
: }
: }
由于,Presenter是通过接口的方式与View进行交互的。在这里,由于View通过Form的形式体现,有时候我们要通过这个接口访问Form的一些属性、方法和事件,需要将相应的成员定义在接口上面,比较麻烦。此时,我们可以选择将这些成员定义在一个接口中,具体View的接口继承该接口就可以了。在这里,我们相当是为所有的View接口创建了“基接口”。作为演示,我现在了Form的三个事件成员定义在街口IViewBase中。
: using System;
: using System.ComponentModell;
: namespace MVPDemo
: {
: public interface IViewBase
: {
: event EventHandler Load;
: event EventHandler Closed;
: event CancelEventHandler Closing;
: }
: }
五、实例演示
上面我通过定义基类和接口为整个编程模型搭建了一个框架,现在我们通过一个具体的例子来介绍该编程模型的应用。我们采用的是一个简单的Windows Forms应用,模拟管理客户信息的场景,逻辑很简单:程序启动的时候显示出所有的客户端列表;用户选择某一客户端,将响应的信息显示在TextBox中以供编辑;对客户端信息进行相应修改之后,点击OK按钮进行保存。整个操作界面如下图所示:
首先,我们创建实体类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 = "", FirstName = "San", LastName = "Zhang", Address="Su zhou"},
: new Customer{ Id = "", FirstName = "Si", LastName = "Li", Address="Shang Hai"}
: };
:
: public void UpdateCustomer(Customer customer)
: {
: for (int i = ; 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>()[];
: }
:
: public Customer[] GetAllCustomers()
: {
: var customers = from customer in _customers
: select customer.Clone();
: return customers.ToArray<Customer>();
: }
: }
: }
接着,我们定义View的接口ICustomerView。ICustomerView定义了两个事件,CustomerSelected在用户从Gird中选择了某个条客户记录是触发,而CustomerSaving则在用户完成编辑点击OK按钮视图提交修改时触发。ICustomerView还定义了View必须完成的三个基本操作:绑定客户列表(ListAllCustomers);显示单个客户信息到TextBox(DisplayCustomerInfo);保存后清空可编辑控件(Clear)。
: using System;
: namespace MVPDemo
: {
: public interface ICustomerView : IViewBase
: {
: event EventHandler<CustomerEventArgs> CustomerSelected;
:
: event EventHandler<CustomerEventArgs> CustomerSaving;
:
: void ListAllCustomers(Customer[] customers);
:
: void DisplayCustomerInfo(Customer customer);
:
: void Clear();
: }
: }
事件参数的类型CustomerEventArgs定义如下,两个属性CustomerId和Customer分别代表客户ID和具体的客户,它们分别用于上面提到的CustomerSelected和CustomerSaving事件。
: using System;
: namespace MVPDemo
: {
: public class CustomerEventArgs : EventArgs
: {
: public string CustomerId
: { get; set; }
:
: public Customer Customer
: { get; set; }
: }
: }
而具体的Presenter定义在如下的CustomerPresenter类型中。在重写的OnViewSet方法中注册View的三个事件:Load事件中调用Model获取所有客户列表,并显示在View的Grid上;CustomerSelected事件中通过事件参数传递的客户ID调用Model获取相应的客户信息,显示在View的可编辑控件上;CustomerSaving则通过事件参数传递的被更新过的客户信息,调用Model提交更新。
: using System.Windows.Forms;
:
: namespace MVPDemo
: {
: public class CustomerPresenter: Presenter<ICustomerView>
: {
: 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来说,仅仅需要实现ICustomerView,并处理响应控件事件即可(主要是用户从Grid中选择某个记录触发的RowHeaderMouseClick事件,以及点击OK的事件)。实际上不需要View亲自处理这些事件,而仅仅需要触发相应的事件,让事件订阅者(Presenter)来处理就可以了。此外还需要重写CreatePresenter方法完成对CustomerPresenter的创建。CustomerView定义如下:
: 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 EventHandler<CustomerEventArgs> CustomerSelected;
:
: public event EventHandler<CustomerEventArgs> 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[].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);
: }
: }
: }
原文链接:谈谈关于MVP模式中V-P交互问题
[转]谈谈关于MVP模式中V-P交互问题的更多相关文章
- MVP模式在Android开发中的应用
一.MVP介绍 随着UI创建技术的功能日益增强,UI层也履行着越来越多的职责.为了更好地细分视图(View)与模型(Model)的功能,让View专注于处理数据的可视化以及与用户的交互.同一 ...
- Android中MVP模式与MVC模式比較(含演示样例)
原文链接 http://sparkyuan.me/ 转载请注明出处 MVP 介绍 MVP模式(Model-View-Presenter)是MVC模式的一个衍生. 主要目的是为了解耦,使项目易于维护. ...
- Java(Android)编程思想笔记03:在Android开发中使用MVP模式
1. MVP模式简介: MVC模式相信大家肯定是比较熟悉的:M-Model-模型.V-View-视图.C-Controller-控制器. MVP作为MVC的演化版本,那么类似的MVP所对应的意义:M- ...
- 应用MVP模式写出可维护的优美Android应用
在Android开发中,我们常常会动辄写出数千行的Java类,而当一个Activity有4.5千行的时候,想找一个逻辑在哪儿就会显得异常痛苦了.比如想在数据加载错误的时候,显示一个提示信息,上上下下得 ...
- 【Android - 框架】之MVP模式的使用
提起MVP架构模式,大家可能首先想到的是它的"前辈"MVC模式.MVC由Model.View.Controller组成,请求从Controller进入后进行业务判断,然后交给Mod ...
- Android上实现MVP模式的途径
今天我想分享我在Android上实现MVP(Model-View-Presenter)模式的方法.如果你对MVP模式还不熟悉,或者不了解为什么要在Android应用中使用MVP模式,推荐你先阅读这篇维 ...
- MVP模式与MVVM模式
1.mvp模式(Model层 Presenter层 View 层) Model层 :数据层(ajax请求) Presenter层:呈现层,view逻辑相关的控制层,控制层可以去调Model去发ajax ...
- MVP模式入门案例
随着UI创建技术的功能日益增强,UI层也履行着越来越多的职责.为了更好地细分视图(View)与模型(Model)的功能,让View专注于处理数据的可视化以及与用户的交互,同时让Model只关系数据的处 ...
- (未完成)【Android】MVP模式初见(一)
最近在阅读郭霖大神的公众号时,分类中架构引起了我的注意. 虽然是个人开发(水平很菜的那种),但最终都要向企业正式项目开发靠近.因此接下来一段时间,主要学习一下MVP架构.Retrofit以及RxJav ...
随机推荐
- Maven环境的搭建
1.本地仓库和apache-mavenbin.zip的下载与解压 <1.apache-mavenbin.zip下载网址 http://maven.apache.org/download.cgi ...
- SpringBoot 初体验
1.Spring Boot 简介 简化Spring应用开发的一个框架 整个Spring技术栈的一个大整合 J2EE开发的一站式解决方案 2.微服务 2014, martin fowler 微服务:架构 ...
- groovy实现循环、交换变量、多赋值、?.运算符
/** * Created by Jxy on 2019/1/3 10:01 * 1.实现循环的方式 * 2.安全导航操作符---?. * 3.一次性赋值给多个变量 */ 0.upto(2){ pri ...
- HBase入门教程
# 背景 最近看到公司一个项目用到hbase, 之前也一直想看下hbase.个人理解Hbase作为一个nosql数据库,逻辑模型感觉跟关系型数据库有点类似.一个table,有row即行,列.不过列是一 ...
- 解决:IDEA springmvc maven 项目搭建完后没有生成 webcontent 目录
前言:发现项目创建好,配置好,写好测试代码,一看没有 webcontent 目录. 问题: 解决方案: ctrl + alt + Shift + S
- JSON和JSONP 实例
来源:http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html 前言: 说到AJAX就会不可避免的面临两个问 ...
- WC2017 游记
你若安好,便是晴天. 其实本来是有一个写的比较详细的游记的……然而后来给断了,懒得补上了,简单一点好了. Day 0 早早爬起来去赶高铁…… 路上没太多可以写的……坐高铁的时候想起来了一些不开心的事情 ...
- 1475 m进制转十进制
1475 m进制转十进制 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 白银 Silver 题解 题目描述 Description 将m进制数n转化成一个十进制数 ...
- LeetCode 514----Freedom Trail
问题描述 In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a ...
- 如何提高 Java 中锁的性能
锁不是问题的根源,锁之间的竞争才是 通常在多线程的代码中遇到性能方面的问题时,一般都会抱怨是锁的问题.毕竟锁会降低程序的运行速度和其较低的扩展性是众所周知的.因此,如果带着这种“常识”开始优化代码,其 ...