Android_MVP学习
2018-07-02 本文已影响0人
柠檬味的香橙
MVP是模型(Model)、视图(View)、主持人(Presenter)的缩写,分别代表项目中3个不同的模块。
模型(Model):负责处理数据的加载或者存储,比如从网络或本地数据库获取数据等;
视图(View):负责界面数据的展示,与用户进行交互,主要是指Fragment ,Activity;
主持人(Presenter):相当于协调者,是模型与视图之间的桥梁,将模型与视图分离开来;
View层与Model层并不直接交互,而是使用Presenter作为View与Model之间的桥梁。其中Presenter中同时持有Viwe层以及Model层的Interface的引用,而View层持有Presenter层Interface的引用。当View层某个界面需要展示某些数据的时候,首先会调用Presenter层的某个接口,然后Presenter层会调用Model层请求数据,当Model层数据加载成功之后会调用Presenter层的回调方法通知Presenter层数据加载完毕,最后Presenter层再调用View层的接口将加载后的数据展示给用户。这就是MVP模式的整个核心过程。

这样分层的好处就是大大减少了Model与View层之间的耦合度。一方面可以使得View层和Model层单独开发与测试,互不依赖。另一方面Model层可以封装复用,可以极大的减少代码量。
- View发生改变,不影响model
- model发生改变,不影响View
- presenter发生改变,只需要改persenter
下面是用MVP模拟登陆的一个简单Demo:






这样一个简单的Demo就实现了。