安卓开发Android开发Android开发经验谈

理解MVP在Android中的应用

2016-07-29  本文已影响384人  jas0nHu

之前对MVP的没有完全理解,在写代码的时候经常出现不知道要把代码写到哪个文件的尴尬,在读MPV架构代码方面也有比较大的困难,再次看了MVP for Android后,重新读了作者在GitHub上的MVP Example后,终于明白了M,V,P三者各自的职能。

Model

  1. 具体的业务逻辑
  2. 业务逻辑执行完后记得回调Presenter,让Presenter去控制视图
  3. 需要调用回调接口回报数据

View

  1. 将界面动作封装等待Presenter的调用

Presenter

  1. 从Model获取数据并调用View里面的方法来展示数据
  2. 调用Model中封装好的业务逻辑函数,并接受Model的回调
  3. 调用View中封装好的页面展示函数,控制视图
  4. 实现Mode的回调接口

总结

  1. 具体的工作都是View(视图细节控制)、Model(业务逻辑细节)来做的,Presenter只是起到了中间人的作用
  2. 从Presenter的类定义中就可以看出它是在利用哪些业务逻辑类(model)来控制哪些视图(View中封装好的界面控制函数)
  3. 为了更好的降低类之间的耦合,model中回调和Presenter中对View的调用都是调用的接口

在Uncle BOb的The Clean Architecture看到了关于Model回调接口回报数据给Presenter的原因,引用如下

For example, consider that the use case needs to call the presenter. However, this call must not be direct because that would violate The Dependency Rule: No name in an outer circle can be mentioned by an inner circle. So we have the use case call an interface (Shown here as Use Case Output Port) in the inner circle, and have the presenter in the outer circle implement it.

我的理解的是:为了防止Model依赖于Presenter,Model只是在调用自己的回调接口,至于谁来实现这个接口,他不管,这样就不会Hard Depent on Presenter了。

Title:理解MVP在Android中的应用
Author:Jason Hu
Created:2016-07-20, 21:01:00
Updated:2016-07-20, 21:53:59
Full URL:http://0xng.com/2016/07/20/理解MVP在Android中的应用/ **
License:** "CC BY-NC-SA 4.0" Keep Link & Author if Distribute.

上一篇下一篇

猜你喜欢

热点阅读