技术开发 频道

NBearV3教程——MVP(Model/View/Presenter)

    Step 2 定义View和Presenter

    2.1 将MVP_Tutorial中的IoC_Tutorial.sln重命名为MVP_Tutorial.sln,并在VS2005开发环境中打开。

    2.2 我们知道MVP模式中,有Model、View和Presenter三个部分。在NBear.MVP中,Model部分,我们直接使用基于NBear.IoC的Service,因此,对于原来的IoC教程的代码,我们只需要额外定义View和Presenter的代码。为了充分解耦M、V、P三部分,我们将用到接口、范型和IoC技术。

    2.3 为sln新增一个名叫ViewInterfaces的类库工程。添加该工程到dist\NBear.Common.dll和Entities工程的引用。在ViewInterfaces中增加一个ISampleView.cs文件,包含如下内容:

using System; using Entities; namespace ViewInterfaces { public interface ISampleView { int CategoryID { get; } Category[] Categories { set; } Product[] ProductsInCategory { set; } } }

    2.4 为sln新增一个名叫PresenterInterfaces的类库工程。添加该工程到dist\NBear.Common.dll、NBear.MVP.dll和Entities工程的引用。在PresenterInterfaces中增加一个ISamplePresenter.cs文件,包含如下内容:

using System; using Entities; using NBear.MVP; namespace PresenterInterfaces { public interface ISamplePresenter : IPresenter { void GetCategories(); void GetProductsInCategory(); } }

    2.5 为sln新增一个名叫PresenterImpls的类库工程。添加该工程到dist\ NBear.Common.dll、NBear.IoC.dll、NBear.MVP.dll、ServiceInterfaces、ViewInterfaces、PresenterInterfaces和Entities工程的引用。在PresenterImpls中增加一个SamplePresenter.cs文件,实现前面定义的ISamplePresenter,包含如下内容:

using System; using System.Collections.Generic; using Entities; using ServiceInterfaces; using PresenterInterfaces; using ViewInterfaces; using NBear.MVP; namespace PresenterImpls { public class SamplePresenter : Presenter<ISampleView, ICategoryService>, ISamplePresenter { ISamplePresenter Members#region ISamplePresenter Members public void GetCategories() { //in presenter we can to additional data filtering, so that services can be reused more. List<Category> categoriesWithProducts = new List<Category>(); foreach (Category item in model.GetAllCategories()) { if (item.Products.Count > 0) { categoriesWithProducts.Add(item); } } view.Categories = categoriesWithProducts.ToArray(); if (categoriesWithProducts.Count > 0) { view.ProductsInCategory = model.GetCategoryByID(categoriesWithProducts[0].CategoryID).Products.ToArray(); } } public void GetProductsInCategory() { view.ProductsInCategory = model.GetCategoryByID(view.CategoryID).Products.ToArray(); } #endregion } }

    2.6 至此,需要的View接口、Presenter接口和实现都定义完了。对PresenterImpls,可以和ServiceImpls一样进行独立的测试。这是MVP模式最大的好处。注意,PresenterImpls中SamplePresenter继承自NBear.MVP中定义的Presenter基类,并实现IPresenter接口。该接口和基类为Presenter提供了对NBear.IoC的封装,在继承类中,可以访问Presenter基类中定义的view和model这两个protected的成员变量,分别访问关联的view和model。下面,我们将修改website以使用这些类。您将看到NBear.MVP通过 NBear.IoC获得的依赖注入能力。

0
相关文章