当前位置:   article > 正文

Thinking In Design Pattern——MVP模式演绎

Thinking In Design Pattern——MVP模式演绎

原文《Thinking In Design Pattern——MVP模式演绎》不知为何丢失了,故重新整理了一遍。

目录

  • What Is MVP
  • Domain Model
  • StubRepositoty
  • IView & Presenter
  • View
  • Ioc容器StructureMap

开篇

忙碌的9月,工作终于落定,新公司里的框架是MVP+Linq,对于MVP虽然不熟,但有MVC的基础,花了两天时间研究了MVP,故作此博文,留作参考。

Model-View-Presenter(模型-视图-呈现器,MVP)模式的重点是让Presenter控制整个表示层的逻辑流。MVP模式由如下三个不同部分组成:

  • 模型表示视图显示或者修改的业务数据,包括业务逻辑和领域相关的逻辑。
  • 视图通过呈现器显示模型数据,并将用户输入委托给呈现器。
  • 呈现器被视图调用来显示从模型中“拉”出来的数据并处理用户输入。

What Is MVP

了解了MVP设计模式后,我以一个简单的例子阐述MVP模式在企业级架构中的应用,如下图给出了企业级分层设计的ASP.NET应用程序的典型体系结构(实际还要更复杂些):

 

下面的我将以一个简单的案例(出自《ASP.NET》设计模式)详解MVP思想的应用,当然MVP和MVC一样都是属于表现层的设计模式,我将参考上述两幅图中的分层思想来创建应用程序,下图为分层体系结构创建完毕时解决方案目录:

OK,接下来我们从头开始来创建我们的应用程序,首先我们要分清楚需求(建立一个简单的购物流程Demo),了解需求后我们再抽象出模型(Category,Product)。

建立简单的领域模型:

  1. namespace Eyes.MVP.Model
  2. {
  3. public class Category
  4. {
  5. public int Id { get; set; }
  6. public string Name { get; set; }
  7. }
  8. }
  1. public class Product
  2. {
  3. public int Id { get; set; }
  4. public Category Category { get; set; }
  5. public string Name { get; set; }
  6. public decimal Price { get; set; }
  7. public string Description { get; set; }
  8. }

接着,为Product和Category添加资源库的契约接口,该接口为业务实体持久化提供了标准方法,我建议把这部分代码放到infrastructure层中:

 

  1. public interface ICategoryRepository
  2. {
  3. IEnumerable<Category> FindAll();
  4. Category FindBy(int id);
  5. }
  6. public interface IProductRepository
  7. {
  8. IEnumerable<Product> FindAll();
  9. Product FindBy(int id);
  10. }

最后添加领域服务类ProductService,基于接口编程的思想使用资源库契约接口(IxxxRepository)来协调Product和Category的操作:

  1. public class ProductService
  2. {
  3. private ICategoryRepository _categoryRepository;
  4. private IProductRepository _productRepository;
  5. public ProductService(ICategoryRepository categoryRepository, IProductRepository productRepository)
  6. {
  7. _categoryRepository = categoryRepository;
  8. _productRepository = productRepository;
  9. }
  10. public Product GetProductBy(int id)
  11. {
  12. return _productRepository.FindBy(id);
  13. }
  14. public IEnumerable<Product> GetAllProductsIn(int categoryId)
  15. {
  16. return _productRepository.FindAll().Where(c => c.Category.Id == categoryId);
  17. }
  18. public Category GetCategoryBy(int id)
  19. {
  20. return _categoryRepository.FindBy(id);
  21. }
  22. public IEnumerable<Category> GetAllCategories()
  23. {
  24. return _categoryRepository.FindAll();
  25. }
  26. public IEnumerable<Product> GetBestSellingProducts()
  27. {
  28. return _productRepository.FindAll().Take(4);
  29. }
  30. }

建立Domain Model之后,需要为资源库(仓储)提供数据,所以创建StubRepository:

StubRepositoty

创建名为StubRepositoty的类库,DataContext为我们的资源库提供数据:

  1. /// <summary>
  2. /// Provider data to repositories
  3. /// </summary>
  4. public class DataContext
  5. {
  6. private readonly List<Product> _products;
  7. private readonly List<Category> _categories;
  8. public DataContext()
  9. {
  10. _categories = new List<Category>();
  11. var hatCategory = new Category {Id = 1, Name = "Hats"};
  12. var gloveCategory = new Category {Id = 2, Name = "Gloves"};
  13. var scarfCategory = new Category {Id = 3, Name = "Scarfs"};
  14. _categories.Add(hatCategory);
  15. _categories.Add(gloveCategory);
  16. _categories.Add(scarfCategory);
  17. _products = new List<Product>
  18. {
  19. new Product {Id = 1, Name = "BaseBall Cap", Price = 9.99m, Category = hatCategory},
  20. new Product {Id = 2, Name = "Flat Cap", Price = 5.99m, Category = hatCategory},
  21. new Product {Id = 3, Name = "Top Hat", Price = 9.99m, Category = hatCategory}
  22. };
  23. _products.Add(new Product {Id = 4, Name = "Mitten", Price = 10.99m, Category = gloveCategory});
  24. _products.Add(new Product {Id = 5, Name = "Fingerless Glove", Price = 13.99m, Category = gloveCategory});
  25. _products.Add(new Product {Id = 6, Name = "Leather Glove", Price = 7.99m, Category = gloveCategory});
  26. _products.Add(new Product {Id = 7, Name = "Silk Scarf", Price = 23.99m, Category = scarfCategory});
  27. _products.Add(new Product {Id = 8, Name = "Woolen", Price = 14.99m, Category = scarfCategory});
  28. _products.Add(new Product {Id = 9, Name = "Warm Heart", Price = 87.99m, Category = scarfCategory});
  29. }
  30. public List<Product> Products
  31. {
  32. get { return _products; }
  33. }
  34. public List<Category> Categories
  35. {
  36. get { return _categories; }
  37. }
  38. }

当数据就为之后,我们就可以实现Model项目中定义的资源库契约接口:

  1. public class ProductRepository : IProductRepository
  2. {
  3. public IEnumerable<Product> FindAll()
  4. {
  5. return new DataContext().Products;
  6. }
  7. public Product FindBy(int id)
  8. {
  9. Product productFound = new DataContext().Products.FirstOrDefault(prod => prod.Id == id);
  10. //set discription
  11. if (productFound != null)
  12. {
  13. productFound.Description = "orem ipsum dolor sit amet, consectetur adipiscing elit." +
  14. "Praesent est libero, imperdiet eget dapibus vel, tempus at ligula. Nullam eu metus justo." +
  15. "Curabitur sit amet lectus lorem, a tempus felis. " +
  16. "Phasellus consectetur eleifend est, euismod cursus tellus porttitor id.";
  17. }
  18. return productFound;
  19. }
  20. }
  21. public class CategoryRepository : ICategoryRepository
  22. {
  23. public IEnumerable<Category> FindAll()
  24. {
  25. return new DataContext().Categories;
  26. }
  27. public Category FindBy(int id)
  28. {
  29. return new DataContext().Categories.FirstOrDefault(cat => cat.Id == id);
  30. }
  31. }

这样我们就完成了StubRepository项目,有关Infrastructure和Repository我不做详细介绍,所以我简单处理。当然本片博客的核心是MVP,接下来详解View和Presenter关系。

View & Presenter

切换Presenter项目中,添加IHomeView接口,这个接口定义了电子商务网页的视图,在首页上显示商品目录以及最畅销的商品:

  1. public interface IHomeView
  2. {
  3. IEnumerable<Category> CategoryList { set; }
  4. }

接着,定义一个IHomePagePresenter接口,这个接口的目的是实现代码松散耦合并有助于测试:

  1. public interface IHomePagePresenter
  2. {
  3. void Display();
  4. }

最后,添加一个HomePagePresenter,这个呈现器从ProductService中检索到的Product和Category数据来填充视图属性,这儿完美体现了Presenter的作用:

  1. public class HomePagePresenter : IHomePagePresenter
  2. {
  3. private readonly IHomeView _view;
  4. private readonly ProductService _productService;
  5. public HomePagePresenter(IHomeView view, ProductService productService)
  6. {
  7. _view = view;
  8. _productService = productService;
  9. }
  10. public void Display()
  11. {
  12. _view.TopSellingProduct = _productService.GetBestSellingProducts();
  13. _view.CategoryList = _productService.GetAllCategories();
  14. }
  15. }

接下来是包含一个分类中所有商品的视图ICategoryProductsView:

  1. public interface ICategoryProductsView
  2. {
  3. int CategoryId { get; }
  4. IEnumerable<Product> CategoryProductList { set; }
  5. IEnumerable<Category> CategoryList { set; }
  6. }

然后再创建CategoryProductsPresenter,他与HomePagePresenter相似:从ProductService中获取到的分类商品来更新视图,但他稍有不同,他要求视图提供CategoryId:

  1. public class CategoryProductsPresenter : ICategoryProductsPresenter
  2. {
  3. private readonly ICategoryProductsView _view;
  4. private readonly ProductService _productService;
  5. public CategoryProductsPresenter(ICategoryProductsView view, ProductService productService)
  6. {
  7. _view = view;
  8. _productService = productService;
  9. }
  10. public void Display()
  11. {
  12. _view.CategoryProductList = _productService.GetAllProductsIn(_view.CategoryId);
  13. _view.Category = _productService.GetCategoryBy(_view.CategoryId);
  14. _view.CategoryList = _productService.GetAllCategories();
  15. }
  16. }

接下来我们还要创建下一个视图用来表示Product的详细视图,该视图显示有关特定商品的详细信息并可以添加到购物车中(Session),在该视图之前我们还需要创建一些支撑类:

  1. public interface IBasket
  2. {
  3. IEnumerable<Product> Items { get; }
  4. void Add(Product product);
  5. }
  6. public class WebBasket : IBasket
  7. {
  8. public IEnumerable<Model.Product> Items
  9. {
  10. get { return GetBasketProducts(); }
  11. }
  12. public void Add(Model.Product product)
  13. {
  14. IList<Product> products = GetBasketProducts();
  15. products.Add(product);
  16. }
  17. private IList<Product> GetBasketProducts()
  18. {
  19. var products = HttpContext.Current.Session["Basket"] as IList<Product>;
  20. if (products == null)
  21. {
  22. products = new List<Product>();
  23. HttpContext.Current.Session["Basket"] = products;
  24. }
  25. return products;
  26. }
  27. }

WebBasket类简单的使用当前会话来存放和检索商品集合,接着我们在添加一个Navigation,用来重定向:

  1. public enum PageDirectory { Basket }
  2. public interface IPageNavigator { void NaviagateTo(PageDirectory page); }

实现IPageNavigator:

  1. public void NaviagateTo(PageDirectory page)
  2. {
  3. switch (page)
  4. {
  5. case PageDirectory.Basket:
  6. HttpContext.Current.Response.Redirect("/Views/Basket/Basket.aspx");
  7. break;
  8. default: break;
  9. }
  10. }

编写好辅助类之后,我们在创建商品详细视图,这儿需要注意一下ProduceId这个属性,和之前一样也是只读的,通过QueryString得到ProductId:

  1. public interface IProductDetailView
  2. {
  3. int ProductId { get; }
  4. string Name { set; }
  5. decimal Price { set; }
  6. string Description { set; }
  7. IEnumerable<Category> CategoryList { set; }
  8. }

接下来,添加一个相应的ProductDetailPresenter(实现IProductDetailPresenter接口):

  1. public class ProductDetailPresenter : IProductDetailPresenter
  2. {
  3. private readonly IProductDetailView _view;
  4. private readonly ProductService _productService;
  5. private readonly IBasket _basket;
  6. private readonly IPageNavigator _pageNavigator;
  7. public ProductDetailPresenter(IProductDetailView view, ProductService productService, IBasket basket,
  8. IPageNavigator pageNavigator)
  9. {
  10. _view = view;
  11. _productService = productService;
  12. _basket = basket;
  13. _pageNavigator = pageNavigator;
  14. }
  15. public void Display()
  16. {
  17. Product product = _productService.GetProductBy(_view.ProductId);
  18. _view.Name = product.Name;
  19. _view.Description = product.Description;
  20. _view.Price = product.Price;
  21. _view.CategoryList = _productService.GetAllCategories();
  22. }
  23. public void AddProductToBasketAndShowBasketPage()
  24. {
  25. Product product = _productService.GetProductBy(_view.ProductId);
  26. _basket.Add(product);
  27. _pageNavigator.NaviagateTo(PageDirectory.Basket);
  28. }
  29. }

最后添加购物车视图,IBasketView接口显示顾客的购物车中的所有商品以及一个用户商品目录导航的商品分类列表:

  1. public interface IBasketView
  2. {
  3. IEnumerable<Category> CategoryList { set; }
  4. IEnumerable<Product> BasketItems { set; }
  5. }

相信接下来你已经驾轻就熟了,创建BasketPresenter,用来控制Model和View之间的数据交互:

  1. public class BasketPresenter : IBasketPresenter
  2. {
  3. private readonly IBasketView _view;
  4. private readonly ProductService _productService;
  5. private readonly IBasket _basket;
  6. public BasketPresenter(IBasketView view, ProductService productService, IBasket basket)
  7. {
  8. _view = view;
  9. _productService = productService;
  10. _basket = basket;
  11. }
  12. public void Display()
  13. {
  14. _view.BasketItems = _basket.Items;
  15. _view.CategoryList = _productService.GetAllCategories();
  16. }
  17. }

这样我们就完成了Presenter项目,接下来我们就可以关注视图实现了,由于篇幅有限,我挑选一个典型模块分析,具体代码可以在此下载:

MVP实现关注点的分离,集中管理相关的逻辑,View关注与UI交互,Model关注与业务逻辑,Presenter协调管理View和Model,是整个体系的核心。Model与View无关,具有极大复用性。 
MVP通过将将主要的逻辑局限于Presenter,是它们具有更好的可测试性。至于并行开发,个人觉得在真正的开发中,意义到不是很大,现在开发这大多是多面手,呵!

Presenter通过接口调用View降低了Presenter对View的依赖,但是View依然可以调用Presenter,从而导致了很多开发人员将Presenter当成了一个Proxy,所以我们的目的是降低View对Presenter的依赖。

“所以我更倾向于View并不知道按钮点击后回发生什么事,如Update数据,但是点击后界面有什么光线,水纹,这个应该是View关心的,View应该更注重的是和用户交互的反应。”着正是本文的观点:View仅仅将请求递交给Presenter,Presenter在适当的时候来驱动View!

View:

为了使布局统一和减少冗余代码,我们将创建Master Page和User Control:

CategoryList.ascx,用来显示所有的目录集合:

为了能让Presenter为他绑定数据,我们需要创建一个方法:

  1. public partial class CategoryList : System.Web.UI.UserControl
  2. {
  3. public void SetCategoriesToDisplay(IEnumerable<Category> categories)
  4. {
  5. this.rptCategoryList.DataSource = categories; this.rptCategoryList.DataBind();
  6. }
  7. }

接下来,再添加一个用户控件ProductList.ascx,用来显示商品的集合:

  1. public partial class ProductList : System.Web.UI.UserControl
  2. {
  3. public void SetProductsToDisplay(IEnumerable<Model.Product> products)
  4. {
  5. this.rptProducts.DataSource = products; this.rptProducts.DataBind();
  6. }
  7. }

最后再添加一个Master Page,并为其添加一个:

  1. <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Shop.master.cs" Inherits="Eyes.MVP.UI.Web.Views.Shared.Shop" %>
  2. <%@ Register src="~/Views/Shared/CategoryList.ascx" tagname="CategoryList" tagprefix="uc1" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" >
  5. <head runat="server">
  6. <title></title>
  7. </head>
  8. <body>
  9. <form id="form1" runat="server">
  10. <div>
  11. <table width="70%">
  12. <tr>
  13. <td colspan="3"><h2><a href="http://archive.cnblogs.com/Views/Home/Index.aspx" target="_blank" rel="nofollow">
  1. public partial class Shop : System.Web.UI.MasterPage
  2. {
  3. public CategoryList CategoryListControl
  4. {
  5. get { return this.CategoryList1; }
  6. }
  7. }

接下来添加一张ProductDetail.aspx页面,因为比较典型,所以我选他来作为分析,让其实现IProductDetailView接口:

  1. public partial class ProductDetail : System.Web.UI.Page, IProductDetailView
  2. {
  3. private IProductDetailPresenter _presenter;
  4. protected void Page_Init(object sender, EventArgs e)
  5. {
  6. _presenter = new ProductDetailPresenter(this, ObjectFactory.GetInstance<ProductService>(),
  7. ObjectFactory.GetInstance<IBasket>(),
  8. ObjectFactory.GetInstance<IPageNavigator>());
  9. }
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. _presenter.Display();
  13. }
  14. public int ProductId
  15. {
  16. get { return int.Parse(Request.QueryString["ProductId"]); }
  17. }
  18. public string Name
  19. {
  20. set { litName.Text = value; }
  21. }
  22. public decimal Price
  23. {
  24. set { litPrice.Text = string.Format("{0:C}", value); }
  25. }
  26. public string Description
  27. {
  28. set { litDescription.Text = value; }
  29. }
  30. public IEnumerable<Model.Category> CategoryList
  31. {
  32. set
  33. {
  34. Shop shopMaster = (Shop) Page.Master;
  35. shopMaster.CategoryListControl.SetCategoriesToDisplay(value);
  36. }
  37. }
  38. protected void btnAddToBasket_Click(object sender, EventArgs e)
  39. {
  40. _presenter.AddProductToBasketAndShowBasketPage();
  41. }
  42. }

这里我想提一下Ioc容器:StructureMap

  Ioc

传统的控制流,从客户端创建服务时(new xxxService()),必须指定一个特定服务实现(并且对服务的程序集添加引用),Ioc容器所做的就是完全将这种关系倒置过来(倒置给Ioc容器),将服务注入到客户端代码中,这是一种推得方式(依赖注入)。术语”控制反转“,即客户放弃代码的控制,将其交给Ioc容器,也就是将控制从客户端代码倒置给容器,所以又有人称作好莱坞原则”不要打电话过来,我们打给你“。实际上,Ioc就是使用Ioc容器将传统的控制流(客户端创建服务)倒置过来,将服务注入到客户端代码中。

总之一句话,客户端代码能够只依赖接口或者抽象类或基类或其他,而不关心运行时由谁来提供具体实现。

使用Ioc容器如StructureMap,首先配置依赖关系(即当向Ioc容器询问特定的类型时将返回一个具体的实现),所以这又叫依赖注入:

  1. public class BootStrapper
  2. {
  3. public static void ConfigureDependencies()
  4. {
  5. ObjectFactory.Initialize(x => { x.AddRegistry<ControllerRegistry>(); });
  6. }
  7. public class ControllerRegistry : Registry
  8. {
  9. public ControllerRegistry()
  10. {
  11. ForRequestedType<ICategoryRepository>().TheDefault.Is.OfConcreteType<CategoryRepository>();
  12. ForRequestedType<IProductRepository>().TheDefault.Is.OfConcreteType<ProductRepository>();
  13. ForRequestedType<IPageNavigator>().TheDefault.Is.OfConcreteType<PageNavigator>();
  14. ForRequestedType<IBasket>().TheDefault.Is.OfConcreteType<WebBasket>();
  15. }
  16. }
  17. }

通常我们希望在启动是配置依赖关系,一般在Application_Start事件中调用ConfigureStructureMap方法:

  1. protected void Application_Start(object sender, EventArgs e) { BootStrapper.ConfigureDependencies();
  2. }

小结

MVP设计模式我匆忙总结了一下,由于经验不足,不足之处,还望多多指点。

转载于:https://my.oschina.net/OceanEyes/blog/381540

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/286324
推荐阅读
相关标签
  

闽ICP备14008679号