Android MVP 简单实例

本文是「吴小龙同学」投稿,MVP其实一直被提及比较多,我的读者们可能有一些人不理解,其实再多的理论比不上一次简单的实践,这篇文章就以一个简单的请求天气功能,来演示Android MVP是如何使用的。可以点击「阅读原文」到原博客!

效果预览

Android MVP 简单实例

准备

MVP流程

Android MVP 简单实例

说明:

步骤1:UI实现View方法,引用Presenter

步骤2:Presenter调用Model,走Model具体逻辑

步骤3:Model逻辑实现,回调Presenter方法

步骤4:Presenter回调View,即回到UI,回调View方法

gradle文件

compile 'com.loopj.android:android-async-http:1.4.9'

说明:请求网络使用async-http

目录结构

Android MVP 简单实例

MVP之V

MainView.java

Android MVP 简单实例

MainActivity

Android MVP 简单实例

Android MVP 简单实例

MVP之P

MainPresenter.java

Android MVP 简单实例

Presenter

Android MVP 简单实例

IMainPresenter

Android MVP 简单实例

MVP之M

MainModel

Android MVP 简单实例

MainModelBean

Android MVP 简单实例

源码地址

https://github.com/WuXiaolong/AndroidMVPSample

总结

MVC模式

视图(View):用户界面。

控制器(Controller):业务逻辑

模型(Model):数据保存

View 传送指令到 Controller

Controller 完成业务逻辑后,要求 Model 改变状态

Model 将新的数据发送到 View,用户得到反馈

MVP模式

使用MVP时,Activity和Fragment变成了MVC模式中View层,Presenter相当于MVC模式中Controller层,处理业务逻辑。每一个Activity都有一个相应的presenter来处理数据进而获取model。

MVVM模式

将 Presenter 改名为 ViewModel,基本上与 MVP 模式完全一致。唯一的区别是,它采用双向绑定(data-binding):View的变动,自动反映在 ViewModel,反之亦然。

上述都是转载,身为一个菜鸟,我对上述的理解是,MainModelBean数据容器,MainModel请求数据并传递数据给IMainPresenterMainPresenter实现接口IMainPresenter,Presenter并把数据传递给MainView。最后MainActivity实现MainView接口更新UI。逻辑更加清晰,代码也可以服用到其他地方。