跟随Google的脚步
https://github.com/googlesamples/android-architecture/tree/todo-mvp/
这是一个类似笔记本的东西,先来看一下项目的整体结构
可以看到每一个包下大致分为Activity、Fragment、Contract、Presenter四个部分,个人认为对包的划分还是一习惯问题,没有什么优劣之分,如果你愿意也可以简单的按M、V、P这样三层来分做三个包。Google这样按功能模块分包的方式可能更清晰一些,结构一目了然。
我们这里只讲这个MVP的整体架构,暂时不管UI的逻辑,所以我们选择一个模块比如addedittask添加一条新的笔记这个包,类图关系如下所示
对于Presenter和View抽象出了各自的BaseInterface,所有功能模块的P和V接口都要继承此Base,然后将P和V放在Contract接口中。而XXXPresenter实现XXXContract.Presenter,XXXFragment实现XXXContract.View,将P和V进一步封装在一起的好处可能在于其连接了P和V,并且实现的时候更方便一些。这里的AddEditTaskPresenter内部持有M层的对象mTasksRepository和V层的对象mAddTaskView,作为中间层这使它连接了M和V,而Activity持有P层的对象mAddEditTaskPresenter。要注意的是该项目中的V层其实并非Activity,而是使用了Fragment,对此Google的解释如下:
Notice also in the following illustration that this version of the app uses fragments, and this is for two reasons:
* The use of both [activities] and [fragments] allows for a better separation of concerns which complements this implementation of MVP. In this version of the app, the Activity is the overall controller which creates and connects views and presenters.
* The use of fragments supports tablet layouts or UI screens with multiple views.
主要还是为了方便适配不同的设备。
那MVP架构具体如何工作的呢,看下图该APP的主界面呈现过程:
可以看到presenter处于中间做为桥梁,从M层获取数据后展现在了V层界面上。